import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, getRepository, getManager, Not, In, Like, IsNull, UpdateResult, Or } from 'typeorm';
import { Video } from './video.entity';
import { LikeVideo } from '../likeVideo/likeVideo.entity';
import { InternetCelebrity } from '../internetCelebrity/internetCelebrity.entity';
import { DeleteTagEnum, EnumInIc, EnumIsHome, IsRewardEnum, OriginalEnum, OverseasEnum, ProfitTypeEnum, SourceEnum, VideoEnum } from './video.enum';
import { CheckEnum, TypeEnum } from '../answer/answer.enum';
import { Answer } from '../answer/answer.entity';
import DataBase from '../../config/database'
import { Platform } from '../platform/platform.entity';
import { MultiImg } from '../multiImg/multiImg.entity';
import { InternetCelebrityGroup } from '../internetCelebrityGroup/internetCelebrityGroup.entity';
import { AnswerInfo } from '../answerInfo/answerInfo.entity';
import { TraceRelaTable } from '../traceRelaTable/traceRelaTable.entity';
import { VideoTag } from '../videoTag/videoTag.entity';
import { Notices } from '../notices/notices.entity';
import { NoticeCheckEnum, NoticeIsDeleteEnum, NoticeTypeEnum } from '../notices/notices.enum';
import { question_store_wx_user, system_wx_user, video_SubAppId } from 'src/setting';
import { WXAPI } from '../../common/wx_api'
import { Reward } from '../reward/reward.entity';
import { payStatusEnum } from '../reward/reward.enum';
import { EnumInternetCelebrityGroupTypeEnum } from '../internetCelebrityGroup/internetCelebrityGroup.enum';
import { RewardSuccess } from '../rewardSuccess/rewardSuccess.entity';
import utils from 'src/common/utils';
import { Setting } from '../setting/setting.entity';
import { WorkTypeEnum } from '../watchRecordIc/watchRecordIc.enum';
import { WatchRecordIc } from '../watchRecordIc/watchRecordIc.entity';
import { Questions } from '../questions/questions.entity';
import { Profit } from '../profit/profit.entity';
import { EnumProfitPostAnswer, profitEnum, profitTypeEnum } from '../profit/profit.enum';
import { WxUser } from '../wxUser/wxUser.entity';
import { WatchRecord } from '../watchRecord/watchRecord.entity';
import GLRandom from 'src/common/GLRandom';
import { UserSetting } from '../userSetting/userSetting.entity';
import { EnumQuestionPostAnswer, QuestionDeleteTag } from '../questions/questions.enum';
import { getQueryVideoField } from 'src/common/sql/video';
import { RechargeFlow } from '../rechargeFlow/rechargeFlow.entity';
let WXAPIOBJ = new WXAPI()
let isFindRobot = ` video.source != 2 and  `
// isFindRobot = ''


import { RedisInstance } from '../../common/redis';
import { WsStartGateway } from '../ws/ws.gateway';
import { ProfitRefund } from '../profitRefund/profitRefund.entity';
import { EnumProfitRefundType, profitRefundStatusEnum } from '../profitRefund/profitRefund.enum';
import { AnswerReportErrors } from '../answerReportErrors/answerReportErrors.entity';
import { RateLimiterService } from '../rateLimiter/rateLimiter.service';
import { RedisCacheService } from '../redisCache/redisCache.service';
import { Redis } from 'ioredis';
import { InjectRedis } from '@nestjs-modules/ioredis';
import { ProfitUnLockHome } from '../profitUnLockHome/profitUnLockHome.entity';
import { EnumProfitUnLockHome_Status } from '../profitUnLockHome/profitUnLockHome.enum';
import { Concern } from '../concern/concern.entity';
import { UnConcern } from '../unconcern/unconcern.entity';
import { writeFileSync } from 'fs';
import { join } from 'path';
import { Timeout } from '@nestjs/schedule';
import { VideoAbroad } from '../videoAbroad/videoAbroad.entity';
import { AnswerAbroad } from '../answerAbroad/answerAbroad.entity';
import { MultiImgAbroad } from '../multiImgAbroad/multiImgAbroad.entity';
const redis_limit = RedisInstance.initRedis();

const RateLimiter = require('async-ratelimiter')

const rateLimiter = new RateLimiter({
  db: redis_limit,
  max: 20,
  duration: 1000 * 60 * 60 * 24,
})




@Injectable()
export class VideoService {
  constructor(
    @InjectRepository(Video)
    private videoRepository: Repository<Video>,
    @InjectRepository(Answer)
    private answerRepository: Repository<Answer>,
    @InjectRepository(Platform)
    private platformRepository: Repository<Platform>,
    @InjectRepository(InternetCelebrity)
    private icRepository: Repository<InternetCelebrity>,
    @InjectRepository(AnswerInfo)
    private answerInfoRepository: Repository<AnswerInfo>,
    @InjectRepository(MultiImg)
    private multiImgRepository: Repository<MultiImg>,
    @InjectRepository(VideoTag)
    private videoTagRepository: Repository<VideoTag>,
    @InjectRepository(Notices)
    private noticesRepository: Repository<Notices>,
    @InjectRepository(Reward)
    private rewardRepository: Repository<Reward>,
    @InjectRepository(InternetCelebrityGroup)
    private internetCelebrityGroupRepository: Repository<InternetCelebrityGroup>,
    @InjectRepository(RewardSuccess)
    private rewardSuccessRepository: Repository<RewardSuccess>,
    @InjectRepository(Setting)
    private settingRepository: Repository<Setting>,
    @InjectRepository(WatchRecordIc)
    private watchRecordIcRepository: Repository<WatchRecordIc>,
    @InjectRepository(Questions)
    private questionsIcRepository: Repository<Questions>,
    @InjectRepository(Profit)
    private profitRepository: Repository<Profit>,
    @InjectRepository(WxUser)
    private wxUserRepository: Repository<WxUser>,
    @InjectRepository(WatchRecord)
    private watchRecordRepository: Repository<WatchRecord>,
    @InjectRepository(LikeVideo)
    private likeVideoRepository: Repository<LikeVideo>,
    @InjectRepository(UserSetting)
    private userSettingRepository: Repository<UserSetting>,
    @InjectRepository(RechargeFlow)
    private rechargeFlowRepository: Repository<RechargeFlow>,
    private readonly wsStartGateway: WsStartGateway,
    @InjectRepository(ProfitRefund)
    private profitRefundRepository: Repository<ProfitRefund>,
    @InjectRepository(AnswerReportErrors)
    private answerReportErrorsRepository: Repository<AnswerReportErrors>,
    private readonly rateLimiter: RateLimiterService,
    private readonly redisCacheService: RedisCacheService,
    @InjectRedis() private readonly redis: Redis,
    @InjectRepository(ProfitUnLockHome)
    private profitUnLockHomeRepository: Repository<ProfitUnLockHome>,
    @InjectRepository(Concern)
    private concernRepository: Repository<Concern>,
    @InjectRepository(UnConcern)
    private unConcernRepository: Repository<UnConcern>,
    @InjectRepository(InternetCelebrity)
    private internetCelebrityRepository: Repository<InternetCelebrity>,
    @InjectRepository(VideoAbroad)
    private videoAbroadRepository: Repository<VideoAbroad>,
    @InjectRepository(AnswerAbroad)
    private answerAbroadRepository: Repository<AnswerAbroad>,
    @InjectRepository(MultiImgAbroad)
    private multiImgAbroadRepository: Repository<MultiImgAbroad>,
  ) { }

  async copyToAll(video_id: number) {
    //查询视频
    let findVideo = await this.videoRepository.findOne({ where: { id: video_id } })

    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      findVideo.isreward = 0
      findVideo.check = CheckEnum.no
      findVideo.original = 1
      delete findVideo.id
      if (findVideo.video_url_source) {
        findVideo.video_url = findVideo.video_url_source
        delete findVideo.video_url_source
      }
      let result = await this.videoRepository.createQueryBuilder(null, queryRunner).insert().into(Video).values(findVideo).execute()
      let video_id = result.identifiers[0].id
      //添加答案
      let answer = new Answer()
      answer.video_id = video_id
      answer.wx_user = system_wx_user
      answer.check = 1
      answer.check_time = new Date()
      answer.create_time = new Date()
      answer.ic_group = findVideo.ic_group
      await this.answerRepository.createQueryBuilder(null, queryRunner).insert().into(Answer).values(answer).execute()

      await queryRunner.commitTransaction()
      await queryRunner.release();
      return { video_id: video_id }
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return { error: err }
    }

  }

  updatePlayVideoUrlToMp4(video_id: number, video_url_source: string): Promise<UpdateResult> {
    return this.videoRepository.update({ id: video_id }, { video_url: video_url_source, video_url_source: '' })
  }

  /**
   * 查询视频和图片各自数量
   */
  async getVideoAndImageCount(wx_user: string): Promise<{ data: [] }> {
    let result = await this.videoRepository.query(`
      select * from (
        -- 视频
        select count(1) total, 'video' as type, 'my' as source from
        video
        where video.wx_user = ? and video.type = 0 and video.check = 1
        union all
        -- 图片
        select count(1) total, 'image' as type, 'my' as source from
        video
        where video.wx_user = ? and video.type = 1 and video.check = 1
        union all
        -- 其他人视频
        select count(1) total, 'video' as type, 'other' as source from
        video
        where video.wx_user != ? and video.type = 0 and video.check = 1
        union all
        -- 其他人图片
        select count(1) total, 'image' as type, 'other' as source from
        video
        where video.wx_user != ? and video.type = 1 and video.check = 1
        union all
        -- 第一堆视频
        select count(1), 'video' as type, 'level1' as source from video
        where video.type = 0 and video.check = 1 
          and video.is_home = 1 
          and video.ic_group is null
          and !(
            video.overseas = 3 and video.profit_type = 1 and video.original = 1
          )
        union all
        -- 第一堆图片
        select count(1), 'image' as type, 'level1' as source from video
        where video.type = 1 and video.check = 1 
          and video.is_home = 1 
          and video.ic_group is null
          and !(
            video.overseas = 3 and video.profit_type = 1 and video.original = 1
          )
        union all
        -- 第二堆视频
        select count(1), 'video' as type, 'level2' as source from video
        where video.type = 0 and video.in_level3 = 0 and
          video.check = 1 and video.delete_tag = 0 and video.ic_group is not null and video.is_home = 1
          and video.id not in (
            select video.id from video
            where video.check = 1 and (
              video.ic_group in (
                select a.id from (
                  select distinct internet_celebrity_group.id from internet_celebrity_group 
                  left join platform on platform.ic_group = internet_celebrity_group.id
                  inner join video on video.ic_group = internet_celebrity_group.id
                  where (
                    (
                      internet_celebrity_group.type = 2 
                    )
                    or(
                      internet_celebrity_group.type = 0 and (
                        platform.platform in (select setting.value from setting where setting.key = 'level3')
                        or (select count(1) from platform where platform.platform != '' and platform.ic_group = internet_celebrity_group.id) = 0
                      )
                    )
                    or (
                      internet_celebrity_group.type = 3
                    )
                  )
                ) a
              )
              or ((video.overseas = 3 or video.overseas = 1) and video.original = 1)
            )
          )
          and video.id not in (
            select video_id from reward_success
            where reward_success.unit_price = 20000
          )
        union all
        -- 第二堆图片
        select count(1), 'image' as type, 'level2' as source from video
        where video.type = 1 and video.in_level3 = 0 and
          video.check = 1 and video.delete_tag = 0 and video.ic_group is not null and video.is_home = 1
          and video.id not in (
            select video.id from video
            where video.check = 1 and (
              video.ic_group in (
                select a.id from (
                  select distinct internet_celebrity_group.id from internet_celebrity_group 
                  left join platform on platform.ic_group = internet_celebrity_group.id
                  inner join video on video.ic_group = internet_celebrity_group.id
                  where (
                    (
                      internet_celebrity_group.type = 2 
                    )
                    or(
                      internet_celebrity_group.type = 0 and (
                        platform.platform in (select setting.value from setting where setting.key = 'level3')
                        or (select count(1) from platform where platform.platform != '' and platform.ic_group = internet_celebrity_group.id) = 0
                      )
                    )
                    or (
                      internet_celebrity_group.type = 3
                    )
                  )
                ) a
              )
              or ((video.overseas = 3 or video.overseas = 1) and video.original = 1)
            )
          )
          and video.id not in (
            select video_id from reward_success
            where reward_success.unit_price = 20000
          )
        union all
        -- 第三堆视频
        select count(1), 'video' as type, 'level3' as source from (
          select distinct video.id from video
          inner join internet_celebrity_group on internet_celebrity_group.id = video.ic_group
          where video.type = 0 and 
          (
            (
              video.overseas = 1 and video.profit_type = 0 and video.original = 1
            )
            or (
              video.overseas = 3 and video.profit_type = 0 and video.original = 1
            )
            or(
              (video.overseas = 0 or video.original = 0) 
              and (
                (
                  internet_celebrity_group.type = 0 and 
                  (
                    internet_celebrity_group.id in (select platform.ic_group from platform inner join setting on setting.value = platform.platform where setting.key = 'level3')
                    or (select count(1) from platform where platform.platform != '' and platform.ic_group = internet_celebrity_group.id) = 0
                  )
                )
                or internet_celebrity_group.type = 3
              )
              and (
                (video.original = 0 and (video.in_ic = 0 or video.in_ic is null))
                or (video.original = 1 and video.in_ic = 0)
              )
            )
            or video.in_level3 = 1
          )
          and video.check = 1 and video.is_home = 1 and video.delete_tag = 0 and video.ic_group is not null and (video.source = 0 or video.source = 2) and (
            video.ic_group in (
              select a.id from (
                select distinct internet_celebrity_group.id from internet_celebrity_group 
                left join platform on platform.ic_group = internet_celebrity_group.id
                inner join video on video.ic_group = internet_celebrity_group.id
                where 
                (
                  (
                    video.overseas = 1 and video.profit_type = 0 and video.original = 1
                  )
                  or (
                    video.overseas = 3 and video.profit_type = 0 and video.original = 1
                  )
                  or(
                    (video.overseas = 0 or video.original = 0) 
                    and (
                      (
                        internet_celebrity_group.type = 0 and 
                        (
                          platform.platform in (select setting.value from setting where setting.key = 'level3')
                          or (select count(1) from platform where platform.platform != '' and platform.ic_group = internet_celebrity_group.id) = 0
                        )
                      )
                      or internet_celebrity_group.type = 3
                    )
                    and (
                      (video.original = 0 and (video.in_ic = 0 or video.in_ic is null))
                      or (video.original = 1 and video.in_ic = 0)
                    )
                  )
                )
              ) a
            )
            or ((video.overseas = 3 or video.overseas = 1) and video.original = 1)
            or video.in_level3 = 1
          )
          and video.id not in (
            select video_id from reward_success
            where reward_success.unit_price = 20000
          )
        ) video
        union all
        -- 第三堆图片
        select count(1), 'image' as type, 'level3' as source from (
          select distinct video.id from video
          inner join internet_celebrity_group on internet_celebrity_group.id = video.ic_group
          where video.type = 1 and (
            (
              video.overseas = 1 and video.profit_type = 0 and video.original = 1
            )
            or (
              video.overseas = 3 and video.profit_type = 0 and video.original = 1
            )
            or(
              (video.overseas = 0 or video.original = 0) 
              and (
                (
                  internet_celebrity_group.type = 0 and 
                  (
                    internet_celebrity_group.id in (select platform.ic_group from platform inner join setting on setting.value = platform.platform where setting.key = 'level3')
                    or (select count(1) from platform where platform.platform != '' and platform.ic_group = internet_celebrity_group.id) = 0
                  )
                )
                or internet_celebrity_group.type = 3
              )
              and (video.in_ic = 0 or video.in_ic is null)
            )
            or video.in_level3 = 1
          )
          and video.check = 1 and video.is_home = 1 and video.delete_tag = 0 and video.ic_group is not null and (video.source = 0 or video.source = 2) and (
            video.ic_group in (
              select a.id from (
                select distinct internet_celebrity_group.id from internet_celebrity_group 
                left join platform on platform.ic_group = internet_celebrity_group.id
                inner join video on video.ic_group = internet_celebrity_group.id
                where (
                  (
                    video.overseas = 1 and video.profit_type = 0 and video.original = 1
                  )
                  or (
                    video.overseas = 3 and video.profit_type = 0 and video.original = 1
                  )
                  or(
                    (video.overseas = 0 or video.original = 0) 
                    and (
                      (
                        internet_celebrity_group.type = 0 and 
                        (
                          platform.platform in (select setting.value from setting where setting.key = 'level3')
                          or (select count(1) from platform where platform.platform != '' and platform.ic_group = internet_celebrity_group.id) = 0
                        )
                      )
                      or internet_celebrity_group.type = 3
                    )
                    and (video.in_ic = 0 or video.in_ic is null)
                  )
                )
              ) a
            )
            or ((video.overseas = 3 or video.overseas = 1) and video.original = 1)
            or video.in_level3 = 1
          )
          and video.id not in (
            select video_id from reward_success
            where reward_success.unit_price = 20000
          )
        ) video
      ) a
    `, [wx_user, wx_user, wx_user, wx_user])

    let look_max = await this.findLookCount()
    console.log(look_max, 'lookmax')
    look_max.map(e => {
      result.push({ source: e.source || 'list', title: (e.source ? '' : '剩余-') + e.level, source_text: e.level, image: e.image, video: e.video })
    })
    // result.push({ source: 'lookmax', source_text: look_max[0].level, image: look_max[0].image, video: look_max[0].video })


    let level3 = result.filter(e => e.source === 'level3')
    if (level3.length > 0) {
      //第三堆国内数量
      let level3_cn = await this.videoRepository.query(`
        select * from (
          -- 第三堆视频
          select count(1) as total, 'video' as type, 'level3' as source from (
            select distinct video.id from video
            inner join internet_celebrity_group on internet_celebrity_group.id = video.ic_group
            where video.type = 0 and 
            (
              video.in_level3 = 1
            )
            and video.check = 1 and video.is_home = 1 and video.delete_tag = 0 and video.ic_group is not null and (video.source = 0 or video.source = 2) and (
              video.in_level3 = 1
            )
            and video.id not in (
              select video_id from reward_success
              where reward_success.unit_price = 20000
            )
          ) video
          union all
          -- 第三堆图片
          select count(1), 'image' as type, 'level3' as source from (
            select distinct video.id from video
            inner join internet_celebrity_group on internet_celebrity_group.id = video.ic_group
            where video.type = 1 and (
              video.in_level3 = 1
            )
            and video.check = 1 and video.is_home = 1 and video.delete_tag = 0 and video.ic_group is not null and (video.source = 0 or video.source = 2) and (
              video.in_level3 = 1
            )
            and video.id not in (
              select video_id from reward_success
              where reward_success.unit_price = 20000
            )
          ) video
        ) video
      `, [])

      let level3_image = level3.find(e => e.type === 'image')
      let level3_image_total = 0
      if (level3_image) {
        level3_image_total = level3_image.total
        let level3_cn_image = level3_cn.find(e => e.type === 'image')
        if (level3_cn_image) {
          level3_image.total = level3_cn_image.total
        }
      }
      let level3_video = level3.find(e => e.type === 'video')
      let level3_video_total = 0
      if (level3_video) {
        level3_video_total = level3_video.total
        let level3_cn_video = level3_cn.find(e => e.type === 'video')
        if (level3_cn_video) {
          level3_video.total = level3_cn_video.total
        }
      }

      let level3_en = [
        { source: 'level3_en', type: 'image', total: level3_image_total - level3_image.total },
        { source: 'level3_en', type: 'video', total: level3_video_total - level3_video.total },
      ]
      result.push(...level3_en)
    }

    //大悬赏
    let bigRewardVideos = await this.videoRepository.query(`
      select count(1) as total, video.type from video
      where video.id in (
        select reward_success.video_id from reward_success
        where reward_success.unit_price = 20000
      ) and video.check = 1
      group by video.type
    `, [])
    let rewardVideoVideo = bigRewardVideos.find(e => e.type == 0)
    let rewardVideoImage = bigRewardVideos.find(e => e.type == 1)
    result.push({ source: 'list', title: '大悬赏', image: rewardVideoImage?.total || 0, video: rewardVideoVideo?.total || 0 })
    return result
  }


  async findLookCount_Level3_cn() {
    let sum_level_r = await this.videoRepository.query(`
      select count(1) as total, video.type from video
      inner join internet_celebrity_group on internet_celebrity_group.id = video.ic_group
      where (
        (
          video.overseas = 1 and video.profit_type = 0 and video.original = 1
        )
        or (
          video.overseas = 3 and video.profit_type = 0 and video.original = 1
        )
        or(
          (video.overseas = 0 or video.original = 0) 
          and (
            (
              internet_celebrity_group.type = 0 and 
              (
                internet_celebrity_group.id in (select platform.ic_group from platform inner join setting on setting.value = platform.platform where setting.key = 'level3')
                or (select count(1) from platform where platform.platform != '' and platform.ic_group = internet_celebrity_group.id) = 0
              )
            )
            or internet_celebrity_group.type = 3
          )
          and (
            (video.original = 0 and (video.in_ic = 0 or video.in_ic is null))
            or (video.original = 1 and video.in_ic = 0)
          )
        )
        or video.in_level3 = 1
      )
      and video.check = 1 and video.is_home = 1 and video.delete_tag = 0 and video.ic_group is not null and (video.source = 0 or video.source = 2) and (
        video.ic_group in (
          select a.id from (
            select distinct internet_celebrity_group.id from internet_celebrity_group 
            left join platform on platform.ic_group = internet_celebrity_group.id
            inner join video on video.ic_group = internet_celebrity_group.id
            where (
              (
                video.overseas = 1 and video.profit_type = 0 and video.original = 1
              )
              or (
                video.overseas = 3 and video.profit_type = 0 and video.original = 1
              )
              or(
                (video.overseas = 0 or video.original = 0) 
                and (
                  (
                    internet_celebrity_group.type = 0 and 
                    (
                      platform.platform in (select setting.value from setting where setting.key = 'level3')
                      or (select count(1) from platform where platform.platform != '' and platform.ic_group = internet_celebrity_group.id) = 0
                    )
                  )
                  or internet_celebrity_group.type = 3
                )
                and (
                  (video.original = 0 and (video.in_ic = 0 or video.in_ic is null))
                  or (video.original = 1 and video.in_ic = 0)
                )
              )
            )
          ) a
        )
        or ((video.overseas = 3 or video.overseas = 1) and video.original = 1)
        or video.in_level3 = 1
      )
      and video.id not in (
        select video_id from reward_success
        where reward_success.unit_price = 20000
      )
      and video.in_level3 = 1
      group by video.type
    `, [])

    let sum_video = Number(sum_level_r.find(e => e.type == 0)?.total || 0)
    let sum_image = Number(sum_level_r.find(e => e.type == 1)?.total || 0)

    let max_level_r = await this.videoRepository.query(`
      select a.total, a.type from (
        select count(1) as total, wx_user.openid, video.type from wx_user
        inner join watch_record on watch_record.wx_user = wx_user.openid
        inner join video on video.id = watch_record.video_id
        where video.wx_user != wx_user.openid and video.id in (
          select video.id from video
          inner join internet_celebrity_group on internet_celebrity_group.id = video.ic_group
          where (
            (
              video.overseas = 1 and video.profit_type = 0 and video.original = 1
            )
            or (
              video.overseas = 3 and video.profit_type = 0 and video.original = 1
            )
            or(
              (video.overseas = 0 or video.original = 0) 
              and (
                (
                  internet_celebrity_group.type = 0 and 
                  (
                    internet_celebrity_group.id in (select platform.ic_group from platform inner join setting on setting.value = platform.platform where setting.key = 'level3')
                    or (select count(1) from platform where platform.platform != '' and platform.ic_group = internet_celebrity_group.id) = 0
                  )
                )
                or internet_celebrity_group.type = 3
              )
              and (
                (video.original = 0 and (video.in_ic = 0 or video.in_ic is null))
                or (video.original = 1 and video.in_ic = 0)
              )
            )
            or video.in_level3 = 1
          )
          and video.check = 1 and video.is_home = 1 and video.delete_tag = 0 and video.ic_group is not null and (video.source = 0 or video.source = 2) and (
            video.ic_group in (
              select a.id from (
                select distinct internet_celebrity_group.id from internet_celebrity_group 
                left join platform on platform.ic_group = internet_celebrity_group.id
                inner join video on video.ic_group = internet_celebrity_group.id
                where (
                  (
                    video.overseas = 1 and video.profit_type = 0 and video.original = 1
                  )
                  or (
                    video.overseas = 3 and video.profit_type = 0 and video.original = 1
                  )
                  or(
                    (video.overseas = 0 or video.original = 0) 
                    and (
                      (
                        internet_celebrity_group.type = 0 and 
                        (
                          platform.platform in (select setting.value from setting where setting.key = 'level3')
                          or (select count(1) from platform where platform.platform != '' and platform.ic_group = internet_celebrity_group.id) = 0
                        )
                      )
                      or internet_celebrity_group.type = 3
                    )
                    and (
                      (video.original = 0 and (video.in_ic = 0 or video.in_ic is null))
                      or (video.original = 1 and video.in_ic = 0)
                    )
                  )
                )
              ) a
            )
            or ((video.overseas = 3 or video.overseas = 1) and video.original = 1)
            or video.in_level3 = 1
          )
          and video.id not in (
            select video_id from reward_success
            where reward_success.unit_price = 20000
          )
          and video.in_level3 = 1
        )
        group by wx_user.openid, video.type
      ) a
      order by a.total desc
    `, [])

    let videos = max_level_r.filter(e => e.type == 0)
    videos.sort((a, b) => Number(b.total) - Number(a.total))
    let max_level1_video = Number(videos[0]?.total || 0)

    let iamges = max_level_r.filter(e => e.type == 1)
    iamges.sort((a, b) => Number(b.total) - Number(a.total))
    let max_level1_image = Number(iamges[0]?.total || 0)

    return { image: sum_image - max_level1_image, video: sum_video - max_level1_video }
  }

  async findLookCount_Level3_en() {
    let sum_level_r = await this.videoRepository.query(`
      select count(1) as total, video.type from video
      inner join internet_celebrity_group on internet_celebrity_group.id = video.ic_group
      where (
        (
          video.overseas = 1 and video.profit_type = 0 and video.original = 1
        )
        or (
          video.overseas = 3 and video.profit_type = 0 and video.original = 1
        )
        or(
          (video.overseas = 0 or video.original = 0) 
          and (
            (
              internet_celebrity_group.type = 0 and 
              (
                internet_celebrity_group.id in (select platform.ic_group from platform inner join setting on setting.value = platform.platform where setting.key = 'level3')
                or (select count(1) from platform where platform.platform != '' and platform.ic_group = internet_celebrity_group.id) = 0
              )
            )
            or internet_celebrity_group.type = 3
          )
          and (
            (video.original = 0 and (video.in_ic = 0 or video.in_ic is null))
            or (video.original = 1 and video.in_ic = 0)
          )
        )
      )
      and video.check = 1 and video.is_home = 1 and video.delete_tag = 0 and video.ic_group is not null and (video.source = 0 or video.source = 2) and (
        video.ic_group in (
          select a.id from (
            select distinct internet_celebrity_group.id from internet_celebrity_group 
            left join platform on platform.ic_group = internet_celebrity_group.id
            inner join video on video.ic_group = internet_celebrity_group.id
            where (
              (
                video.overseas = 1 and video.profit_type = 0 and video.original = 1
              )
              or (
                video.overseas = 3 and video.profit_type = 0 and video.original = 1
              )
              or(
                (video.overseas = 0 or video.original = 0) 
                and (
                  (
                    internet_celebrity_group.type = 0 and 
                    (
                      platform.platform in (select setting.value from setting where setting.key = 'level3')
                      or (select count(1) from platform where platform.platform != '' and platform.ic_group = internet_celebrity_group.id) = 0
                    )
                  )
                  or internet_celebrity_group.type = 3
                )
                and (
                  (video.original = 0 and (video.in_ic = 0 or video.in_ic is null))
                  or (video.original = 1 and video.in_ic = 0)
                )
              )
            )
          ) a
        )
        or ((video.overseas = 3 or video.overseas = 1) and video.original = 1)
      )
      and video.id not in (
        select video_id from reward_success
        where reward_success.unit_price = 20000
      )
      and video.in_level3 != 1
      group by video.type
    `, [])

    let sum_video = Number(sum_level_r.find(e => e.type == 0)?.total || 0)
    let sum_image = Number(sum_level_r.find(e => e.type == 1)?.total || 0)

    let max_level_r = await this.videoRepository.query(`
      select a.total, a.type from (
        select count(1) as total, wx_user.openid, video.type from wx_user
        inner join watch_record on watch_record.wx_user = wx_user.openid
        inner join video on video.id = watch_record.video_id
        where video.wx_user != wx_user.openid and video.id in (
          select video.id from video
          inner join internet_celebrity_group on internet_celebrity_group.id = video.ic_group
          where (
            (
              video.overseas = 1 and video.profit_type = 0 and video.original = 1
            )
            or (
              video.overseas = 3 and video.profit_type = 0 and video.original = 1
            )
            or(
              (video.overseas = 0 or video.original = 0) 
              and (
                (
                  internet_celebrity_group.type = 0 and 
                  (
                    internet_celebrity_group.id in (select platform.ic_group from platform inner join setting on setting.value = platform.platform where setting.key = 'level3')
                    or (select count(1) from platform where platform.platform != '' and platform.ic_group = internet_celebrity_group.id) = 0
                  )
                )
                or internet_celebrity_group.type = 3
              )
              and (
                (video.original = 0 and (video.in_ic = 0 or video.in_ic is null))
                or (video.original = 1 and video.in_ic = 0)
              )
            )
          )
          and video.check = 1 and video.is_home = 1 and video.delete_tag = 0 and video.ic_group is not null and (video.source = 0 or video.source = 2) and (
            video.ic_group in (
              select a.id from (
                select distinct internet_celebrity_group.id from internet_celebrity_group 
                left join platform on platform.ic_group = internet_celebrity_group.id
                inner join video on video.ic_group = internet_celebrity_group.id
                where (
                  (
                    video.overseas = 1 and video.profit_type = 0 and video.original = 1
                  )
                  or (
                    video.overseas = 3 and video.profit_type = 0 and video.original = 1
                  )
                  or(
                    (video.overseas = 0 or video.original = 0) 
                    and (
                      (
                        internet_celebrity_group.type = 0 and 
                        (
                          platform.platform in (select setting.value from setting where setting.key = 'level3')
                          or (select count(1) from platform where platform.platform != '' and platform.ic_group = internet_celebrity_group.id) = 0
                        )
                      )
                      or internet_celebrity_group.type = 3
                    )
                    and (
                      (video.original = 0 and (video.in_ic = 0 or video.in_ic is null))
                      or (video.original = 1 and video.in_ic = 0)
                    )
                  )
                )
              ) a
            )
            or ((video.overseas = 3 or video.overseas = 1) and video.original = 1)
          )
          and video.id not in (
            select video_id from reward_success
            where reward_success.unit_price = 20000
          )
          and video.in_level3 != 1
        )
        group by wx_user.openid, video.type
      ) a
      order by a.total desc
    `, [])

    let videos = max_level_r.filter(e => e.type == 0)
    videos.sort((a, b) => Number(b.total) - Number(a.total))
    let max_level1_video = Number(videos[0]?.total || 0)

    let iamges = max_level_r.filter(e => e.type == 1)
    iamges.sort((a, b) => Number(b.total) - Number(a.total))
    let max_level1_image = Number(iamges[0]?.total || 0)

    return { image: sum_image - max_level1_image, video: sum_video - max_level1_video }
  }


  async findLookCount_Level2() {
    let sum_level2_r = await this.videoRepository.query(`
      select count(1) as total, video.type
      from video
      where video.check = 1 and video.in_level3 = 0 and video.delete_tag = 0 and video.ic_group is not null and video.is_home = 1
      and video.id not in (
        select video.id from video
        where video.check = 1 and (
          video.ic_group in (
            select a.id from (
              select distinct internet_celebrity_group.id from internet_celebrity_group 
              left join platform on platform.ic_group = internet_celebrity_group.id
              inner join video on video.ic_group = internet_celebrity_group.id
              where (
                (
                  internet_celebrity_group.type = 2 
                )
                or(
                  internet_celebrity_group.type = 0 and (
                    platform.platform in (select setting.value from setting where setting.key = 'level3')
                    or (select count(1) from platform where platform.platform != '' and platform.ic_group = internet_celebrity_group.id) = 0
                  )
                )
                or (
                  internet_celebrity_group.type = 3
                )
              )
            ) a
          )
          or ((video.overseas = 3 or video.overseas = 1) and video.original = 1)
        )
      )
      and video.id not in (
        select video_id from reward_success
        where reward_success.unit_price = 20000
      )
      group by video.type
    `, [])

    let sum_video = Number(sum_level2_r.find(e => e.type == 0).total || 0)
    let sum_image = Number(sum_level2_r.find(e => e.type == 1).total || 0)

    let max_level1_r = await this.videoRepository.query(`
      select a.total, a.type from (
        select count(1) as total, wx_user.openid, video.type from wx_user
        inner join watch_record on watch_record.wx_user = wx_user.openid
        inner join video on video.id = watch_record.video_id
        where video.wx_user != wx_user.openid and video.check = 1 and video.in_level3 = 0 and video.delete_tag = 0 and video.ic_group is not null and video.is_home = 1
          and video.id not in (
            select video.id from video
            where video.check = 1 and (
              video.ic_group in (
                select a.id from (
                  select distinct internet_celebrity_group.id from internet_celebrity_group 
                  left join platform on platform.ic_group = internet_celebrity_group.id
                  inner join video on video.ic_group = internet_celebrity_group.id
                  where (
                    (
                      internet_celebrity_group.type = 2 
                    )
                    or(
                      internet_celebrity_group.type = 0 and (
                        platform.platform in (select setting.value from setting where setting.key = 'level3')
                        or (select count(1) from platform where platform.platform != '' and platform.ic_group = internet_celebrity_group.id) = 0
                      )
                    )
                    or (
                      internet_celebrity_group.type = 3
                    )
                  )
                ) a
              )
              or ((video.overseas = 3 or video.overseas = 1) and video.original = 1)
            )
          )
          and video.id not in (
            select video_id from reward_success
            where reward_success.unit_price = 20000
          )
        group by wx_user.openid, video.type
      ) a
      order by a.total desc
    `, [])
    let videos = max_level1_r.filter(e => e.type == 0)
    videos.sort((a, b) => Number(b.total) - Number(a.total))
    let max_level1_video = Number(videos[0].total || 0)

    let iamges = max_level1_r.filter(e => e.type == 1)
    iamges.sort((a, b) => Number(b.total) - Number(a.total))
    let max_level1_image = Number(iamges[0].total || 0)

    return { image: sum_image - max_level1_image, video: sum_video - max_level1_video }
  }


  async findLookCount_Level1() {
    let sum_level1_r = await this.videoRepository.query(`
      select count(1) as total, video.type
      from video
      where video.check = 1 
        and video.is_home = 1 
        
        and video.id not in (
          select video_id from reward_success
          where reward_success.unit_price = 20000
        ) 
        and video.ic_group is null
        and !(
          video.overseas = 3 and video.profit_type = 1 and video.original = 1
        )
      group by video.type
    `, [])

    let sum_video = Number(sum_level1_r.find(e => e.type == 0).total || 0)
    let sum_image = Number(sum_level1_r.find(e => e.type == 1).total || 0)

    let max_level1_r = await this.videoRepository.query(`
      select a.total, a.type from (
        select count(1) as total, wx_user.openid, video.type from wx_user
        inner join watch_record on watch_record.wx_user = wx_user.openid
        inner join video on video.id = watch_record.video_id
        where video.wx_user != wx_user.openid and video.check = 1
            and video.is_home = 1 
            and video.id not in (
              select video_id from reward_success
              where reward_success.unit_price = 20000
            ) 
            and video.ic_group is null
            and !(
              video.overseas = 3 and video.profit_type = 1 and video.original = 1
            )
        group by wx_user.openid, video.type
      ) a
      order by a.total desc
    `, [])

    let videos = max_level1_r.filter(e => e.type == 0)
    videos.sort((a, b) => Number(b.total) - Number(a.total))
    let max_level1_video = Number(videos[0].total || 0)

    let iamges = max_level1_r.filter(e => e.type == 1)
    iamges.sort((a, b) => Number(b.total) - Number(a.total))
    let max_level1_image = Number(iamges[0].total || 0)

    return { image: sum_image - max_level1_image, video: sum_video - max_level1_video }
  }

  async findLookCount() {
    let level1 = await this.findLookCount_Level1()
    let level2 = await this.findLookCount_Level2()
    let level3_cn = await this.findLookCount_Level3_cn()
    let level3_en = await this.findLookCount_Level3_en()

    let level1_sum = level1.image + level1.video
    let level2_sum = level2.image + level2.video
    let level3_cn_sum = level3_cn.image + level3_cn.video
    let level3_en_sum = level3_en.image + level3_en.video
    let sum: any = level1
    let level_txt = '第一堆'

    let list = []
    list.push({ level: '第一堆', source: 'lookmax', image: level1.image, video: level1.video, sum: level1_sum })
    list.push({ level: '第二堆', image: level2.image, video: level2.video, sum: level2_sum })
    list.push({ level: '第三堆国内', image: level3_cn.image, video: level3_cn.video, sum: level3_cn_sum })
    list.push({ level: '第三堆国外', image: level3_en.image, video: level3_en.video, sum: level3_en_sum })

    return list

  }

  getQueryVideoField(wx_user: string, tableName, profit_count?: string, other_filed?: string): { sql: string, beforeParams: string[], afterParams: string[] } {
    return getQueryVideoField(wx_user, tableName, profit_count, other_filed)
  }

  async getVideoOtherParams(ids, findAnswerIds?: [], wx_user?: string) {
    if (ids.length === 0) {
      return { answerList: [], multiImg: [] }
    }
    let sql = []
    ids.map(e => {
      sql.push(` b.video_id = ? `)
    })
    let sqlText = ''
    if (sql.length > 0) {
      sqlText = ` and (${sql.join(' or ')})`
    }

    let sqlText_Answer = ''
    if (findAnswerIds) {
      let sqlAnswer = []
      findAnswerIds.map(e => {
        sqlAnswer.push(` b.video_id = ? `)
      })
      if (sqlAnswer.length > 0) {
        sqlText_Answer = ` and (${sqlAnswer.join(' or ')})`
      }
    } else {
      sqlText_Answer = sqlText
    }
    let answerList: any = []
    if (findAnswerIds && findAnswerIds.length === 0) {
      answerList = []
    } else {
      answerList = await this.videoRepository.query(`
        select b.id,b.video_id,b.wx_user,b.create_time,b.check,b.check_time,b.type,b.answer_template_id
          ,b.id as answer_id,c.use_wx_user,e.platform,e.ic_name,e.img,e.img_id, c.status as profit_status, b.id_card as id_card,b.reject_auto_time
        from answer b
        left join profit as c on c.answer_id = b.id
        left join answer_info as e on e.answer_id = b.id
        where b.delete_tag = 0 ${sqlText_Answer}
        order by e.create_time desc
      `, findAnswerIds || ids)
    }

    let multiImg = await this.videoRepository.query(`
      select b.*,d.img as multi_img,b.id as answer_id,
        (
          select profit.use_wx_user from profit
          where profit.answer_id = b.id and profit.use_wx_user = ?
          limit 0,1
        ) as use_wx_user
      from answer b
      left join multi_img as d on d.video_id = b.video_id
      where b.delete_tag = 0 ${sqlText}
      order by d.cover desc,d.id asc
    `, [wx_user, ...ids])

    return { answerList, multiImg }
  }

  async insertQuestionProfit(wx_user: string) {
    let list = await this.questionsIcRepository.query(`
      select questions.video_id, reward.unit_price - reward.service_charge as unit_price,reward.service_charge,questions.wx_user,answer.id as answer_id,reward.id as reward_id
      from questions
      inner join reward on reward.video_id = questions.video_id
      inner join video on video.id = questions.video_id
      inner join answer on answer.video_id = video.id and answer.check = 1
      left join profit on profit.answer_id = answer.id and profit.author_wx_user = ? and profit.use_wx_user = questions.wx_user
      where video.wx_user = ? and answer_time is not null and answer_time <= ? and profit.answer_id is null and reward.pay_status = 1
    `, [wx_user, wx_user, new Date()])
    if (list.length > 0) {
      let insertList: Profit[] = []
      //插入收益
      list.map(e => {
        let profit = new Profit()
        profit.answer_id = e.answer_id
        profit.author_wx_user = wx_user
        profit.use_wx_user = e.wx_user
        profit.status = profitEnum.entry
        profit.create_time = new Date()
        profit.update_time = new Date()
        profit.unit_price = e.unit_price
        profit.service_charge = e.service_charge
        profit.type = profitTypeEnum.consume
        insertList.push(profit)
      })
      let db: DataBase = new DataBase()
      let connection = await db.getConnection()
      const queryRunner = connection.createQueryRunner()
      await queryRunner.connect()
      // 开始事务
      await queryRunner.startTransaction()
      try {
        //插入
        await this.profitRepository.createQueryBuilder(null, queryRunner).insert().into(Profit).values(insertList).execute()
        //修改悬赏为使用
        await this.rewardRepository.createQueryBuilder(null, queryRunner).update({ pay_status: payStatusEnum.used }).where({ id: In(list.map(e => e.reward_id)) }).execute()

        await queryRunner.commitTransaction()
        await queryRunner.release();
      } catch (err) {
        // 有错误做出回滚更改
        await queryRunner.rollbackTransaction()
        await queryRunner.release();
      }
    }
  }

  //提问
  async findAll_MyQuestioin(skip: number, take: number, wx_user?: string): Promise<{ data: [], total: [], answer: [], multiImg: [], rewardAnswerList: [] }> {
    // await this.insertQuestionProfit(wx_user)
    let { sql, beforeParams, afterParams } = this.getQueryVideoField(wx_user, `
      (
        select * from (
          select video.*, questions.post_answer, questions.create_time as question_time from questions
          left join video on video.id = questions.video_id
          where questions.wx_user = ? and questions.delete_tag = 0
          union
          select video.*, questions.post_answer, video.create_time as question_time from video
          left join questions on questions.video_id = video.id
          where video.wx_user = ? and video.original = 0 and video.isreward = 0 and video.id not in (
            select video_id from questions
            where questions.wx_user = ?
          )
          union
          select video.*, questions.post_answer, video.create_time as question_time from video
          left join questions on questions.video_id = video.id
          inner join reward_success on reward_success.video_id = video.id
          where video.wx_user = ? and video.original = 0 and video.isreward = 1 and video.id not in (
            select video_id from questions
            where questions.wx_user = ?
          )
        ) a
        order by a.question_time desc
      ) video
    `, undefined, `, video.create_time, video.post_answer`)
    let dataList = await this.videoRepository.query(`
      select
        ${sql}
      order by video.question_time desc
      limit ?,?
    `, [...beforeParams, wx_user, wx_user, wx_user, wx_user, wx_user, ...afterParams, skip, take])
    dataList.map(e => {
      if (e.authen_work || e.otherNetwork || e.otherNetwork_ic_info) {
        e.workSource = 'ic'
        if (e.original == 0) {
          if (e.post_answer == 1) {
            e.is_question_answer = true
          } else {
            e.is_question_answer = false
            e.workSource = 'question'
          }
        }
      } else if (e.ic_group) {
        e.workSource = 'lib'
      } else {
        e.workSource = 'question'
      }
    })
    // dataList.filter(e => e.unit_price).map(e => {
    //   e.unit_price = Number(e.unit_price) / 100
    //   e.service_charge = Number(e.service_charge) / 100
    // })
    let findAnswerList = dataList.filter(e => {
      if (utils.validIsNull(e.post_answer)) return true
      if (e.post_answer == 1) {
        if (e.original == 0 && e.video_author == wx_user && e.big_reward_answer == wx_user) {
          e.is_question_answer = false
        } else {
          e.is_question_answer = true
        }
        return true
      }
    })

    let { answerList, multiImg } = await this.getVideoOtherParams(dataList.map(e => e.id), dataList.map(e => e.id), wx_user)
    let sumCount = await this.videoRepository.query(`
      select count(1) as sumCount from video
      where (video.original = 0 and video.wx_user = ? and video.isreward = 0) or video.id in (
        select video_id from questions
        where questions.wx_user = ? and questions.delete_tag = 0
      ) or (
        video.original = 0 and video.wx_user = ? and video.isreward = 1 and video.id in (
          select video_id from reward_success
        )
      )
    `, [wx_user, wx_user, wx_user])

    let checkAnswerList = answerList.filter(e => e.check == 1)
    //查询没通知的
    let noticesSql = []
    let noticesSql_Params = []
    checkAnswerList.map(findA => {
      noticesSql.push(` (notices.video_id = ? and notices.answer_id = ?)`)
      noticesSql_Params.push(findA.video_id)
      noticesSql_Params.push(findA.id)
    })
    let noticesSql_Text = ''
    if (noticesSql.length > 0) {
      noticesSql_Text = ' and (' + noticesSql.join(' or ') + ')'
    }
    let yesNoticesList = await this.videoRepository.query(`
      select * from notices
      where notices.type = ? and notices.wx_user = ? and notices.check = 1 ${noticesSql_Text}
    `, [NoticeTypeEnum.question_is_answer, wx_user, ...noticesSql_Params])


    //收到答案添加通知，2024年5月15日03:27:06 改为自动服务通知
    // findAnswerList = findAnswerList.filter(e => {
    //   let findA = checkAnswerList.find(d => d.video_id == e.id)
    //   return findA && !yesNoticesList.find(c => c.video_id == findA.video_id && c.answer_id == findA.id && c.check == 1)
    // })
    // findAnswerList.map(async (e) => {
    //   let findA = checkAnswerList.find(d => d.video_id == e.id)
    //   if(findA){
    //     //添加通知
    //     let notice = new Notices()
    //     notice.create_time = e.answer_time
    //     notice.video_id = findA.video_id
    //     notice.answer_id = findA.id
    //     notice.wx_user = wx_user
    //     notice.check = 1
    //     notice.type = NoticeTypeEnum.question_is_answer
    //     await this.noticesRepository.insert(notice)
    //   }
    // })

    //查询悬赏金额
    let videoRewardList = []
    let rewardVideoIdSql = []
    dataList.filter(e => e.isreward).map(e => {
      let item = {
        video_id: e.id,
      }
      videoRewardList.push(item)
      rewardVideoIdSql.push(` reward_success.video_id = ? `)
    })
    if (videoRewardList.length > 0) {
      let rewardList = await this.rewardSuccessRepository.find({ where: videoRewardList })
      this.setRewardPrice(dataList, rewardList)
    }

    //我悬赏过，并且我的悬赏有答案了
    let rewardAnswerList: any = []
    if (rewardVideoIdSql.length > 0) {
      let rewardVideoIdSql_Text = ''
      if (rewardVideoIdSql.length > 0) {
        rewardVideoIdSql_Text = ' and (' + rewardVideoIdSql.join(' or ') + ')'
      }
      rewardAnswerList = await this.rewardSuccessRepository.query(`
        select reward_success.wx_user, reward_success.video_id from reward_success
        inner join answer on answer.video_id = reward_success.video_id
        where answer.check = 1 and reward_success.wx_user = ? ${rewardVideoIdSql_Text}
      `, [wx_user, ...videoRewardList.map(e => e.video_id)])
    }
    return { data: dataList, total: sumCount[0].sumCount, answer: answerList, multiImg, rewardAnswerList }
  }

  /**
   * 根据id模糊查询
   * @param skip
   * @param take
   * @param id
   * @returns
   */
  async findAll_Like_Id(skip: number, take: number, wx_user: string, id: string, isQuestion?: boolean): Promise<Video[]> {

    // select video.* from video
    // inner join wx_user on wx_user.openid = video.wx_user
    // inner join user_setting on user_setting.wx_user = video.wx_user
    // where video.check = 1 and video.id_card = ? and user_setting.key = 'overseas' and user_setting.value = 1 and video.delete_tag = 0
    // UNION
    let sql = `
      select distinct video.* from video
        inner join internet_celebrity_group on internet_celebrity_group.id = video.ic_group
        inner join platform on platform.ic_group = internet_celebrity_group.id
        where video.check = 1 and video.id_card = ? and video.delete_tag = 0 and 
        (
          (
            video.overseas = 1 and video.profit_type = 1 and video.original = 1
          )
          or(
            (video.overseas = 0 or video.original = 0) 
            and internet_celebrity_group.type = 0 and (platform.platform in (select setting.value from setting where setting.key = 'level3'))
            and (
              (video.original = 0 and video.in_ic = 1)
              or (video.original = 1 and video.in_ic = 0)
            )
          )
          or (
            video.overseas = 3 and video.original = 1
          )
        )
      order by video.create_time desc
      limit ?,?`
    return await this.videoRepository.query(sql, [id, skip, take])
  }

  //作品
  async findAll_MyOriginal(skip: number, take: number, wx_user?: string, searchType?: string, overseas?: number): Promise<{ data: [], total: [], answer: [], multiImg: [] }> {
    let sql = '', params = [], sql_total = '', params_total = []
    let beforeParams = [wx_user, wx_user, wx_user, wx_user, wx_user, wx_user, wx_user]
    let afterParams = [wx_user, wx_user]
    //虚拟网红
    if (overseas == 3) {
      let result = this.getQueryVideoField(wx_user, `
      (
        select a.*,
          (
            select v.id from video as v
            where v.id = a.id and v.check = 1 and v.ic_group in (
              select internet_celebrity_group.id as ic_group from internet_celebrity_group
              left join video on video.ic_group = internet_celebrity_group.id
              left join platform on platform.ic_group = internet_celebrity_group.id
              where (
                (
                  internet_celebrity_group.type = 2 
                  and internet_celebrity_group.wx_user in (
                    select user_setting.wx_user from user_setting where user_setting.key = 'overseas' and user_setting.value = 1
                  )
                )
                or 
                platform.platform in (select setting.value from setting where setting.key = 'level3')
                or
                (video.overseas = 3 and video.original = 1)
              )
            ) 
          ) as workSource
        from video a
        left join answer on answer.video_id = a.id
        where a.wx_user = ?
          and ((a.ic_group in (
            select internet_celebrity_group.id as ic_group from internet_celebrity_group
            where internet_celebrity_group.type != 2
          ) and answer.check = 1 and answer.wx_user = a.wx_user) or a.check = 0) and a.overseas != 1 and a.original = 1 and a.delete_tag = 0
        order by a.create_time desc
        limit ?,?
      ) video`, undefined, ',video.workSource')

      beforeParams = result.beforeParams
      afterParams = result.afterParams
      sql = `
        select distinct ${result.sql}
      `
      params = [...beforeParams, wx_user, skip, take, ...afterParams]
      sql_total = `
        select count(1) as sumCount from video a
        left join answer on answer.video_id = a.id
        where a.wx_user = ?
          and ((a.ic_group in (
            select internet_celebrity_group.id as ic_group from internet_celebrity_group
            where internet_celebrity_group.type != 2
          ) and answer.check = 1 and answer.wx_user = a.wx_user) or a.check = 0 ) and a.overseas != 1 and a.original = 1 and a.delete_tag = 0
      `
      params_total = [wx_user]
    } else {
      let result = this.getQueryVideoField(wx_user, `
      (
        select distinct a.*, 1 as workSource
        from video a
        where a.overseas = 1 and a.wx_user = ? and original = 1
        order by a.create_time desc
        limit ?,?
      ) video`)
      beforeParams = result.beforeParams
      afterParams = result.afterParams
      //认证后
      sql = `
        select ${result.sql}
      `
      params = [...beforeParams, wx_user, skip, take, ...afterParams]
      sql_total = `
        select count(1) as sumCount
        from video a
        where a.overseas = 1 and a.wx_user = ? and original = 1
        order by a.create_time desc
      `
      params_total = [wx_user]
    }
    let dataList: any = await this.videoRepository.query(sql, params)
    let sumCount: any = await this.videoRepository.query(sql_total, params_total)
    dataList.filter(e => e.workSource).map(e => {
      e.workSource = 'ic'
    })

    let { answerList, multiImg } = await this.getVideoOtherParams(dataList.map(e => e.id), undefined, wx_user)


    return { data: dataList, total: sumCount[0].sumCount, answer: answerList, multiImg: multiImg }
  }

  //回答
  async findAll_MyAnswer(skip: number, take: number, wx_user?: string): Promise<{ data: [], total: [], answer: [], multiImg: [] }> {
    let { sql, beforeParams, afterParams } = this.getQueryVideoField(wx_user, `
    (
      select distinct *,
        (
          select questions.post_answer from questions
          where questions.wx_user = ? and questions.video_id = video.id
        ) as post_answer,
        (
          select v.id from video as v
          where v.id = video.id and v.check = 1 and v.ic_group in (
            select internet_celebrity_group.id as ic_group from internet_celebrity_group
            left join video on video.ic_group = internet_celebrity_group.id
            left join platform on platform.ic_group = internet_celebrity_group.id
            where (
              (
                internet_celebrity_group.type = 2 and internet_celebrity_group.wx_user in (
                  select user_setting.wx_user from user_setting where user_setting.key = 'overseas' and user_setting.value = 1
                )
              ) or 
              (
                internet_celebrity_group.type = 0 and platform.platform in (select setting.value from setting where setting.key = 'level3')
              ) or (
                internet_celebrity_group.type = 3
              ) or (
                (video.overseas = 3 or video.overseas = 1) and video.original = 1
              )
            )
          )
        ) as workSource
      from (
        select video.*,
          (
            select answer.update_time from answer
            where answer.video_id = video.id and answer.wx_user = ?
            order by update_time desc
            limit 0,1
          ) as answer_update_time
        from video
        where video.id in (
          select video_id from answer
          where answer.wx_user = ? and answer.delete_tag = 0 and answer.type = 0
        )
      ) video
      order by video.answer_update_time desc
      limit ?,?
    ) video`, `(select count(1) from profit c
    where c.answer_id = b.id and c.unit_price > 0) as profit_count,  video.post_answer, video.workSource`)
    let dataList = await this.videoRepository.query(`
      select distinct ${sql}
    `, [...beforeParams, wx_user, wx_user, wx_user, skip, take, ...afterParams])

    dataList.filter(e => e.workSource).map(e => {
      e.workSource = 'ic'
    })

    dataList.filter(e => e.post_answer == 1).map(e => {
      e.is_question_answer = true
      delete e.question_answer_time
    })


    let video_ids = dataList.map(e => ({ video_id: e.id }))

    let sumCount = await this.videoRepository.query(`
      select count(1) as sumCount from(
        select b.id 
        from video b
        inner join answer a on a.video_id = b.id
        where a.wx_user = ? and a.delete_tag = 0 and a.type = 0
        group by b.id
      )a
    `, [wx_user])

    let { answerList, multiImg } = await this.getVideoOtherParams(dataList.map(e => e.id), undefined, wx_user)
    answerList.map(e => {
      let findData = dataList.find(c => c.id == e.video_id)
      if (findData) {
        findData.answer_id_card = e.id_card
      }
    })


    return { data: dataList, total: sumCount[0].sumCount, answer: answerList, multiImg: multiImg }
  }


  /**
   * 查询收藏视频
   * @param skip
   * @param take
   * @param wx_user
   * @returns
   */
  async findAll_By_Wx_User(skip: number, take: number, wx_user: string): Promise<{ data: [], total: [], answer: [], multiImg: [] }> {
    let result = this.getQueryVideoField(wx_user, `
    (
      select video.*,
        (
          select v.id from video v
          inner join internet_celebrity_group on internet_celebrity_group.id = v.ic_group
          left join platform on platform.ic_group = internet_celebrity_group.id
          where v.id = video.id and v.check = 1 and (
            -- 认证用户的作品
            (
              v.overseas = 1 and v.original = 1
            )
            -- 非认证用户的作品
            or (
              v.overseas = 3 and v.original = 1
            )
            or(
              -- 视频库 和 提问
              (v.overseas = 0 or v.original = 0) 
              -- 视频库是tk 或者是虚拟网红
              and (
                (internet_celebrity_group.type = 0 and (platform.platform in (select setting.value from setting where setting.key = 'level3')))
                or internet_celebrity_group.type = 3
              )
              and (
                -- 提问必须进入主页
                (v.original = 0 and (v.in_ic = 0 or v.in_ic is null))
                or v.original = 1
              )
            )
          )
          limit 0,1
        ) as workSource
      from video
      inner join wx_like_video as likeV on likeV.video_id = video.id
      where likeV.wx_user = ? and likeV.delete_tag = 0
    ) video inner join wx_like_video on wx_like_video.video_id = video.id and wx_like_video.wx_user = ? `, '', ',wx_like_video.last_time, video.workSource')
    let beforeParams = result.beforeParams
    let afterParams = result.afterParams
    let sql = `
      select distinct ${result.sql}
        order by wx_like_video.last_time desc
        limit ?,?
    `
    console.log(sql, 'sq')
    let dataList = await this.videoRepository.query(sql, [...beforeParams, wx_user, wx_user, ...afterParams, skip, take])
    dataList.filter(e => e.workSource).map(e => {
      e.workSource = 'ic'
    })

    let { answerList, multiImg } = await this.getVideoOtherParams(dataList.map(e => e.id), undefined, wx_user)
    let sumCount = await this.videoRepository.query(`
      select count(1) as sumCount
      from video
      inner join wx_like_video as likeV on likeV.video_id = video.id
      where likeV.wx_user = ?
    `, [wx_user])
    return { data: dataList, total: sumCount[0].sumCount, answer: answerList, multiImg: multiImg }
  }

  async findAll_MyWorksTotal(wx_user: string) {
    let list = await this.videoRepository.query(`
      select count(1) as sumCount from video
      where (video.original = 0 and video.wx_user = ? and video.isreward = 0) or video.id in (
        select video_id from questions
        where questions.wx_user = ? and questions.delete_tag = 0
      ) or (
        video.original = 0 and video.wx_user = ? and video.isreward = 1 and video.id in (
          select video_id from reward_success
        )
      )
      union all
      select count(1) as sumCount from(
        select b.id 
        from video b
        inner join answer a on a.video_id = b.id
        where a.wx_user = ? and a.delete_tag = 0 and a.type = 0
        group by b.id
      )a
      union all
      select count(1) as sumCount
      from video
      inner join wx_like_video as likeV on likeV.video_id = video.id
      where likeV.wx_user = ?
      union all
      select count(1) as sumCount
      from video
      where video.original = 1 and video.overseas = 1 and video.profit_type = 1 and wx_user = ? and source = 0
      union all
      select count(1) as sumCount
      from video
      where video.original = 1 and video.overseas = 1 and video.profit_type = 0 and wx_user = ? and source = 0
    `, [wx_user, wx_user, wx_user, wx_user, wx_user, wx_user, wx_user])
    //查询是否认证
    let findOverseas = await this.userSettingRepository.findOne({ where: { wx_user: wx_user, key: 'overseas' } })
    let originalSumCount: any
    if (findOverseas && Number(findOverseas.value ?? 0) == 1) {
      originalSumCount = await this.videoRepository.query(`
        select count(1) as sumCount
        from video a
        where a.overseas = 1 and a.wx_user = ? and original = 1
        order by a.create_time desc
      `, [wx_user])
    } else {
      originalSumCount = await this.videoRepository.query(`
        select count(1) as sumCount from video a
        left join answer on answer.video_id = a.id
        where a.wx_user = ?
          and ((a.ic_group in (
            select internet_celebrity_group.id as ic_group from internet_celebrity_group
            where internet_celebrity_group.type != 2
          ) and answer.check = 1 and answer.wx_user = a.wx_user) or a.check = 0 ) and a.overseas != 1 and a.original = 1
      `, [wx_user])
    }
    let total = { question: 0, original: 0, collection: 0, answer: 0, works_level1: 0, works_level2: 0 }
    if (originalSumCount.length > 0) {
      total.original = originalSumCount[0].sumCount || 0
    }
    total.question = list[0].sumCount || 0
    total.answer = list[1].sumCount || 0
    total.collection = list[2].sumCount || 0
    total.works_level2 = list[3].sumCount || 0
    total.works_level1 = list[4].sumCount || 0
    return total
  }

  setVideoAnswer_Wx_App(findAnswerResult: any, currentIsGroup: any) {
    let e: any = {
      profit_result: [],
      profit_result_img: [],
      profit_result_img_avatar: [],

    }
    //自己回答审核通过，或者自己产生利润（返回答案）
    if (findAnswerResult.length > 0) {
      let answer = []
      let imgs = []
      let img_ids = []
      let avatar_img = []
      let avatar_id = []
      findAnswerResult.map(async c => {
        answer.push(`${c.platform}:${c.ic_name}:${c.account || ''}`)
        imgs.push(c.img)
        img_ids.push(c.img_id)
        avatar_img.push(c.avatar_img)
        avatar_id.push(c.avatar_id)
        e.profit_works = c.profit_works
      })
      e.profit_result = answer
      e.profit_result_img = imgs
      e.profit_result_img_avatar = avatar_img
    }
    if ((e.profit_result || e.profit_result_img || e.profit_result_img_avatar) && currentIsGroup?.length > 0) {
      //如果有关联的网红信息
      let answer = []
      let imgs = []
      let img_ids = []
      let avatar_img = []
      let avatar_id = []
      currentIsGroup.map(async c => {
        answer.push({
          platform: c.platform,
          ic_name: c.ic_name,
          account: c.account
        })

        imgs.push(c.img)
        img_ids.push(c.img_id)
        avatar_img.push(c.avatar_img)
        avatar_id.push(c.avatar_id)
      })
      e.profit_result = answer
      e.profit_result_img = imgs
      e.profit_result_img_avatar = avatar_img
    }
    return e
  }

  async rejectReward(video_id: number, wx_user: string, answer_id: number) {
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      await this.rewardRepository.createQueryBuilder(null, queryRunner).update({ pay_status: payStatusEnum.reject }).where({ video_id: video_id, wx_user: wx_user }).execute()
      await this.rewardSuccessRepository.createQueryBuilder(null, queryRunner).delete().where({ video_id: video_id, wx_user: wx_user }).execute()
      //修改用户原来的收益表数据
      let nowTime = new Date()
      await this.profitRepository.createQueryBuilder(null, queryRunner).update({ status: profitEnum.refoundSuccess }).where({ answer_id: answer_id, use_wx_user: wx_user }).execute()
      //修改问题的发货时间
      await this.questionsIcRepository.createQueryBuilder(null, queryRunner).update({ answer_time: nowTime, post_answer: EnumQuestionPostAnswer.yes }).where({ video_id: video_id, wx_user: wx_user }).execute()
      await WXAPIOBJ.clearPayWallet(wx_user)
      await queryRunner.commitTransaction()
      await queryRunner.release();
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }

  unableVideo(video) {
    let id = video.id
    for (let key in video) {
      video[key] = undefined
    }
    video.id = id
    video.unable = true
  }

  /**
   * 查询视频详情
   * @param video_key
   * @param wx_user
   * @returns
   */
  async findOne_By_Video_id(video_id: number, wx_user: string, uid: number, original: any,
    level: any, source: any, main: any, not_answer: boolean): Promise<{ video: [], answer: [], multiImg: [] }> {
    let isShare = uid && uid > 0
    if (!uid || uid <= 0) {
      let findWxUser = await this.wxUserRepository.findOne({ where: { openid: wx_user } })
      if (findWxUser) {
        uid = findWxUser.id
      }
    }
    let { sql, beforeParams, afterParams } = this.getQueryVideoField(wx_user, `
      (
        
        select video.*, 
          (
            select wx_user.openid from profit
            left join answer on answer.video_id = ? and answer.check = 1
            inner join wx_user on (wx_user.openid = profit.use_wx_user or wx_user.openid = answer.wx_user) and wx_user.id = ?
            where profit.answer_id = answer.id and (profit.status = 0 or profit.status = 1 or profit.status = 3)
            limit 0,1
          ) as answer_author_wx_user,
          answer.id as answer_id,
          (
            select questions.post_answer from questions
            where questions.wx_user = ? and questions.video_id = video.id
          ) as post_answer,
          (
            select unit_price from reward_success
            where reward_success.video_id = video.id and reward_success.wx_user = ?
            limit 0,1
          ) as share_reward,
          (
            select video.id from video
            inner join internet_celebrity_group on internet_celebrity_group.id = video.ic_group
            left join platform on platform.ic_group = internet_celebrity_group.id
            where video.id = ? and video.check = 1 and (
              -- 认证用户的作品
              (
                video.overseas = 1 and video.original = 1
              )
              -- 非认证用户的作品
              or (
                video.overseas = 3 and video.original = 1
              )
              or(
                -- 视频库 和 提问
                (video.overseas = 0 or video.original = 0) 
                -- 视频库是tk 或者是虚拟网红
                and (
                  (internet_celebrity_group.type = 0 and (platform.platform in (select setting.value from setting where setting.key = 'level3')))
                  or internet_celebrity_group.type = 3
                )
                and (
                  -- 提问必须进入主页
                  (video.original = 0 and (video.in_ic = 0 or video.in_ic is null))
                  or video.original = 1
                )
              )
            )
            limit 0,1
          ) as workSource,
          (
            select v.id from video as v
            inner join platform on platform.ic_group = v.ic_group
            inner join internet_celebrity_group on internet_celebrity_group.id = v.ic_group
            where v.id = video.id and v.check = 1 and v.source = 2 and v.ic_group is not null
              and v.id not in (
                select video.id from video
                where video.check = 1 and video.source = 2 and (
                  video.ic_group in (
                    select a.id from (
                      select distinct internet_celebrity_group.id from internet_celebrity_group 
                      left join platform on platform.ic_group = internet_celebrity_group.id
                      inner join video on video.ic_group = internet_celebrity_group.id
                      where (
                        (
                          internet_celebrity_group.type = 2 
                        )
                        or(
                          internet_celebrity_group.type = 0 and platform.platform in (select setting.value from setting where setting.key = 'level3')
                        )
                        or (
                          internet_celebrity_group.type = 3 
                        )
                      )
                    ) a
                  )
                  or ((video.overseas = 3 or video.overseas = 1) and video.original = 1)
                )
              )
            limit 0,1
          ) as is_lib
        from video
        left join answer on answer.video_id = video.id and answer.check = 1
        where video.id = ? and video.delete_tag = 0
      ) video
    `, undefined, `, video.create_time, video.answer_author_wx_user, video.answer_id, 
      video.post_answer, video.share_reward, video.workSource, video.is_home, video.is_lib
    `)
    let dataList = await this.videoRepository.query(`
      select 
        ${sql}
    `, [...beforeParams, video_id, uid, wx_user, wx_user, video_id, video_id, video_id, ...afterParams])
    let { answerList, multiImg } = await this.getVideoOtherParams(dataList.map(e => e.id), dataList.map(e => e.id), wx_user)

    let currentVideo = dataList.find(e => e.id == video_id)
    if (!currentVideo) {
      return { video: [], answer: [], multiImg: [] }
    }
    dataList.filter(e => e.post_answer).map(e => {
      if (e.post_answer == 1) {
        e.is_question_answer = true
      }
      delete e.post_answer
    })

    dataList.filter(e => e.workSource).map(e => {
      e.workSource = 'ic'
    })
    dataList.filter(e => e.is_lib).map(async e => {
      e.workSource = 'lib'
      //查询视频是否同提问并且删除了
      let findQuestion: Questions = await this.questionsIcRepository.findOne({ where: { wx_user: wx_user, video_id: video_id, delete_tag: QuestionDeleteTag.yes } })
      if (findQuestion) {
        e.is_question_delete = true
      }

      delete e.is_lib
    })

    //查询当前用户uid
    let findNowUid: WxUser = await this.wxUserRepository.findOne({ where: { openid: wx_user } })
    let nowUid = findNowUid ? findNowUid.id : ''
    let bIsQuestion = false

    if (!main) {
      //第二堆视频
      if (level == 2) {
        //查询分享者是否回答过并且回答被拒绝
        let findAnswerReject = await this.answerRepository.query(`
          select answer.* from answer
          inner join wx_user on wx_user.openid = answer.wx_user
          where answer.video_id = ? and wx_user.id = ? and (
            answer.check = 0
          )
        `, [video_id, uid])
        let findQuestion: Questions = await this.questionsIcRepository.findOne({ where: { wx_user: wx_user, video_id: video_id } })
        if (findAnswerReject.length > 0) {
          //查询被分享者是否有过同提问，如果没有同提问直接视频不见
          if (!findQuestion) {
            //查询当前用户是否回答过
            let findNowUserAnswer = await this.answerRepository.findOne({ where: { video_id: video_id, wx_user: wx_user, delete_tag: 0 } })
            //没有回答过视频直接不见
            if (!findNowUserAnswer) {
              dataList = []
            }
          } else {
            //如果被分享者提问了，给被分享者发答案，被分享者拿到答案的时间跟分享者被拒的时间一致
            //分享者的拒绝时间
            let rejectTime = findAnswerReject[0].reject_auto_time || findAnswerReject[0].check_time
            if (findQuestion.answer_time && rejectTime && findQuestion.answer_time.getTime() != rejectTime.getTime()) {
              console.log('同步提问时间')
              // await this.questionsIcRepository.update({id: findQuestion.id}, {answer_time: rejectTime})
            }
            //查询是否已经花过钱了
            let findProfit = await this.profitRepository.query(`
              select profit.* from profit 
              inner join answer on answer.id = profit.answer_id
              where answer.video_id = ? and answer.check = 1 and answer.delete_tag = 0 and profit.use_wx_user = ?
            `, [video_id, wx_user])
            //花过钱了，答案发货时间更新为分享者的回答被拒时间
            if (findProfit.length > 0) {
              // if(findProfit[0].delivery_time && rejectTime && findProfit[0].delivery_time.getTime() != rejectTime.getTime()){
              //   console.log('同步答案时间')
              //   await this.profitRepository.update({id: findProfit[0].id}, {delivery_time: rejectTime, update_time: new Date()})
              // }
              currentVideo.is_profit_result = true
              currentVideo.is_question_answer = true
            } else {
              currentVideo.is_question_answer = true
              currentVideo.source_author_question_delete = true
            }
          }
        } else {
          //分享者点击原始链接，查询当前用户是否已有答案并且删除提问了，点击链接看不到视频了
          if (nowUid === uid) {
            //分享者没点过同提问，被分享者点同提问并且拿到答案了，分享者不能看视频
            let findBQuestionPostAnswer = await this.questionsIcRepository.findOne({ where: { video_id: video_id, rela_questions_wx_user: wx_user, post_answer: EnumQuestionPostAnswer.yes } })
            if (!findQuestion && findBQuestionPostAnswer) {
              not_answer = true
              dataList = []
            } else if (findQuestion?.delete_tag === QuestionDeleteTag.yes) {
              dataList = []
            }
          } else {
            //被分享者，查看分享者的链接
            let findQuestionList = await this.questionsIcRepository.query(`
              select * from questions
              inner join wx_user on wx_user.openid = questions.wx_user
              where wx_user.id = ? and questions.video_id = ?
            `, [uid, video_id])
            if (findQuestionList.length > 0) {
              findQuestion = findQuestionList[0]
            } else {
              findQuestion = undefined
            }
            //被分享者点击分享者链接
            if (isShare && findQuestion?.delete_tag === QuestionDeleteTag.yes) {
              //被分享者没同提问，直接看不到视频
              let findShareQuestion = await this.questionsIcRepository.query(`
                select * from questions
                where questions.video_id = ? and questions.wx_user = ? and questions.delete_tag = 0
              `, [video_id, wx_user])
              if (findShareQuestion.length === 0) {
                dataList = []
              } else {
                currentVideo.source_author_question_delete = true
              }
            }
          }
        }
      } else if (level == 1 && currentVideo.workSource != 'ic') {
        //第一堆,被分享者点链接,并且视频没进第三堆
        if (nowUid !== uid) {
          //查询分享者的回答有没有被采纳
          let findIsAccept = await this.answerRepository.query(`
            select * from answer
            inner join wx_user on wx_user.openid = answer.wx_user
            where answer.video_id = ? and wx_user.id = ? and answer.check = 1 and answer.delete_tag = 0
          `, [video_id, uid])
          //分享者的回答被采纳了，被分享者看不见视频
          if (findIsAccept.length > 0) {
            //查询被分享者是否同提问或则回答过
            let findIsAnswerOrQuestion = await this.answerRepository.query(`
              select answer.id from answer
              where answer.wx_user = ? and answer.video_id = ? and answer.delete_tag = 0
              union ALL
              select questions.id from questions
              where questions.wx_user = ? and questions.video_id = ?
            `, [wx_user, video_id, wx_user, video_id])
            //没有同提问后者回答过，视频直接不见
            if (findIsAnswerOrQuestion.length === 0) {
              dataList = []
            }
          } else {
            //查询自己是否被拒并且已删除
            let findMyAnswerReject = await this.answerRepository.query(`
              select answer.* from answer
              where answer.video_id = ? and answer.wx_user = ? and answer.delete_tag = 1
                and (
                  answer.check = 0
                )
            `, [video_id, wx_user])
            if (findMyAnswerReject.length > 0) {
              dataList = []
            } else {
              //查询分享者是否回答过并且回答被拒绝
              let findAnswerReject = await this.answerRepository.query(`
                select answer.* from answer
                inner join wx_user on wx_user.openid = answer.wx_user
                where answer.video_id = ? and wx_user.id = ? and (
                  answer.check = 0
                )
              `, [video_id, uid])
              if (findAnswerReject.length > 0) {
                //没有同提问，视频不见了
                let findQuestion: Questions = await this.questionsIcRepository.findOne({ where: { wx_user: wx_user, video_id: video_id } })
                //没有回答过
                let findIsAnswer: Answer = await this.answerRepository.findOne({ where: { video_id: video_id, wx_user: wx_user } })
                if (!findQuestion && !findIsAnswer) {
                  dataList = []
                }
              }
            }
          }
        } else {
          //查询分享者是否回答过并且回答被拒绝
          let findAnswerReject = await this.answerRepository.query(`
            select answer.* from answer
            inner join wx_user on wx_user.openid = answer.wx_user
            where answer.video_id = ? and wx_user.id = ? and answer.delete_tag = 1
            and (
              answer.check = 0
            )
          `, [video_id, uid])
          if (findAnswerReject.length > 0) {
            dataList = []
          }
        }
      } else {
        //查询用户的提问状态
        //如果提问被删除了，视频直接显示不见了
        let findQuestion = await this.questionsIcRepository.findOne({ where: { video_id: video_id, wx_user: wx_user, delete_tag: QuestionDeleteTag.yes } })
        if (findQuestion) {
          dataList = []
        }
      }

      //如果是分享链接
      if (isShare) {
        // dataList.filter(e => e.is_question_answer).map(e => e.isQuestion = true)
        let notCollectionVideo = dataList.find(e => e.collectionSource == undefined)
        if (notCollectionVideo) {
          //查询分享者的收藏状态
          let findCollection = await this.likeVideoRepository.query(`
            select wx_like_video.source,wx_like_video.wx_user from wx_like_video
            inner join wx_user on wx_user.openid = wx_like_video.wx_user
            where wx_user.id = ? and wx_like_video.video_id = ?
          `, [uid, video_id])
          if (findCollection.length > 0) {
            if (findCollection[0].wx_user == wx_user || notCollectionVideo.otherNetwork_ic_info) {
              notCollectionVideo.collectionSource = findCollection[0].source
            }
          }
        }
      }
      //作品分享
      if (original) {
        if (currentVideo.workSource === 'ic' && currentVideo.video_author === wx_user) {
          currentVideo.look_answer = true
        } else if (currentVideo.otherNetwork_ic_info || currentVideo.workSource === 'lib') {
          currentVideo.look_answer = true
        }
        let notWorkSource = dataList.find(e => !e.workSource)
        if (notWorkSource) {
          //当前视频是不是分享者的作品
          let findOtherNetWork = await this.videoRepository.query(`
            select * from video
            inner join answer on answer.video_id = video.id
            where answer.check = 1 and video.wx_user = answer.wx_user and video.id = ?
          `, [video_id])
          if (findOtherNetWork.length > 0) {
            notWorkSource.workSource = 'ic'
            notWorkSource.otherNetwork_ic_info = true
          }
        }
      }

      //如果看a分享的，并且不是b自己分享的
      if (isShare && !dataList.find(e => e.workSource == 'ic') && dataList.length > 0) {
        let findWxUser = await this.wxUserRepository.findOne({ where: { openid: wx_user } })
        if (findWxUser?.id != uid) {
          //b也提问了
          let findQuestion = await this.questionsIcRepository.query(`
            select questions.* from questions
            inner join answer on answer.video_id = questions.video_id
            where questions.video_id = ? and questions.wx_user = ? and answer.check = 1
          `, [video_id, wx_user, video_id, wx_user])
          if (findQuestion.length > 0) {
            //b同提问，b拿到答案了
            if (findQuestion[0].post_answer == 1) {
              currentVideo.is_question_answer = true
              currentVideo.source_author_question_delete = true
              bIsQuestion = true
            } else {
              //如果是a 回答的，并且回答被采纳 
              let findAIsAnswerAccept = await this.answerRepository.query(`
                select answer.id from answer
                inner join wx_user on wx_user.openid = answer.wx_user
                where answer.check = 1 and answer.delete_tag = 0 and wx_user.id = ? and answer.video_id = ?
              `, [uid, video_id])
              if (findAIsAnswerAccept.length > 0) {
                currentVideo.is_question_answer = true
                currentVideo.source_author_question_delete = true
              }
            }
          } else {
            //b没提问，a拿到答案了
            let findAAnswer = await this.questionsIcRepository.query(`
              select * from questions
              inner join wx_user on wx_user.openid = questions.wx_user
              where wx_user.id = ? and questions.video_id = ? and questions.post_answer = 1
            `, [uid, video_id])
            if (findAAnswer.length > 0) {
              if (not_answer) {
                dataList = []
              } else {
                currentVideo.is_question_answer = true
                // currentVideo.isQuestion = true
              }
            }
          }

        }
      } else if (dataList.find(e => e.workSource == 'ic') && source === 'home') {
        currentVideo.look_answer = true
        //在主页分享的是网红作品，直接看出处
        //a是否已经看了
        let findProfit = await this.profitRepository.query(`
          select * from profit
          inner join answer on answer.id = profit.answer_id
          inner join wx_user on wx_user.openid = profit.use_wx_user
          where wx_user.id = ? and profit.status != 4 and answer.video_id = ?
          limit 0,1
        `, [uid, video_id])
        //a看了，b直接看
        if (findProfit.length > 0) {
          currentVideo.is_profit_result = true
        }
      }
    } else if (!dataList.find(e => e.check == 1)) {
      dataList = []
    }

    let isAnswer = false
    if (!bIsQuestion) {
      dataList.filter(e => e.workSource != 'ic' && (e.answer_author_wx_user || e.collection_share_profit || e.collection_payment_on_behalf_profit)).map(e => {
        delete e.answer_author_wx_user
        e.getAnswerInfo = true
        isAnswer = true
      })
    }
    if (isAnswer && dataList.length > 0) {
      answerList.map(e => {
        e.use_wx_user = wx_user
      })
      const user_answer = await this.answerRepository.query(`
        select e.*,a.ic_group,b.id as profit_works,a.type as video_type from answer b
        left join answer_info as e on e.answer_id = b.id
        inner join video a on a.id = b.video_id
        where b.video_id = ? and b.check = 1 and b.delete_tag = 0
        order by e.create_time desc
      `, [video_id])

      let icGroup = []
      if (user_answer.length === 0 || user_answer[0].ic_group) {
        // 后台关联的答案
        icGroup = await this.platformRepository.query(`
          select distinct a.id as id_platform,a.platform,a.wx_user,b.id as id_ic,b.name as ic_name,b.img,b.img_id,b.avatar_img,b.avatar_id,b.account from platform a
          inner join internet_celebrity b on b.platform = a.id and b.wx_user = a.wx_user
          where a.ic_group in (select ic_group from video where video.id = ?)
          order by a.id asc
        `, [video_id])
      }

      let answerResult = this.setVideoAnswer_Wx_App(user_answer, icGroup)
      let findVideo = dataList[0]
      if (findVideo && answerResult) {
        findVideo.profit_result = answerResult.profit_result
        findVideo.profit_result_img = answerResult.profit_result_img
        findVideo.profit_result_img_avatar = answerResult.profit_result_img_avatar

        //如果当前视频的网红关联了真实网红
        let relaIcAnswerList = await this.videoRepository.query(`
          select distinct wx_user.name as ic_name, wx_user.avatar_img, wx_user.id_card,wx_user.id as wx_user_id,
            (
              select count(1) from video as v
              where v.ic_group = internet_celebrity_group_rela_ic_info.ic_group_rela_ic_info and v.profit_type = 1
            ) as count_look_full_video
          from wx_user
          inner join internet_celebrity_group on internet_celebrity_group.wx_user = wx_user.openid
          inner join internet_celebrity_group_rela_ic_info on internet_celebrity_group_rela_ic_info.ic_group_rela_ic_info = internet_celebrity_group.id
          inner join video on video.ic_group = internet_celebrity_group_rela_ic_info.ic_group
          where video.id = ?
        `, [video_id])
        findVideo.relaIcAnswerList = relaIcAnswerList

        //查找当前用户是否有此视频的悬赏并且还没有发答案
        let findRejectReward = await this.rewardSuccessRepository.query(`
          select * from reward_success
          where reward_success.video_id not in (
            select answer.video_id from profit
            inner join answer on answer.id = profit.answer_id
            where answer.video_id = ? and profit.use_wx_user = ?
          ) and reward_success.video_id = ? and reward_success.wx_user = ?
        `, [video_id, wx_user, video_id, wx_user])
        if (findRejectReward.length > 0) {
          //退回悬赏
          await this.rejectReward(video_id, wx_user, findVideo.answer_id)
        }

      }
    }

    //查询悬赏金额
    let videoRewardList = []
    let rewardVideoIdSql = []
    dataList.map(e => {
      let item = {
        video_id: e.id,
      }
      videoRewardList.push(item)
      rewardVideoIdSql.push(` reward_success.video_id = ? `)
    })
    if (videoRewardList.length > 0) {
      let rewardList = await this.rewardSuccessRepository.find({ where: videoRewardList })
      this.setRewardPrice(dataList, rewardList)
    }

    //查询是否收藏
    // if(dataList.length === 0){
    //   let findCollection = await this.likeVideoRepository.findOne({where:{wx_user: wx_user, video_id: video_id}})
    //   if(findCollection){
    //     dataList = []
    //   }
    // }

    if (not_answer && dataList.length === 0) {
      dataList = [{ emptyVideo: true, id: video_id, emptyVideoText: '问题已解决' }]
    }


    return { video: dataList, answer: answerList, multiImg: multiImg }
  }

  /**
   * 查询视频列表
   * @param video_key
   * @param wx_user
   * @returns
   */
  async findOne_By_Video_Id_List(video_id_list: [string], wx_user?: string): Promise<{ video: [], answer: [], multiImg: [] }> {
    let videoWhere = [wx_user, wx_user]
    let videoSql = []
    video_id_list.map(e => {
      videoWhere.push(e)
      videoSql.push(`video.id = ?`)
    })

    let videoSqlText = videoSql.join(' or ')
    let videoList = await this.videoRepository.query(`
        select
          video.id as id,
          video.video_id as video_id,
          video.video_url as video_url,
          video.video_cover as video_cover,
          video.video_key as video_key,
          video.video_ratio as video_ratio,
          video.type,
          video.original,
          lv.id as like_count,
          video.profit_type,
          video.ic_group,
          (select sum(unit_price) from reward_success where reward_success.video_id = video.id) as isreward,
          video.check,
          video.wx_user as video_author,
          video.overseas,
          wx_user.id as wx_user_id,
          wx_user.avatar_img,
          wx_user.name as ic_name,
          (
            select internet_celebrity.avatar_img from internet_celebrity where internet_celebrity.ic_group = video.ic_group
            order by internet_celebrity.id asc
            limit 0,1
          ) as avatar_img_ic,
          (
            select internet_celebrity.name from internet_celebrity where internet_celebrity.ic_group = video.ic_group
            order by internet_celebrity.id asc
            limit 0,1
          ) as ic_name_ic,
          (
            select id from concern where concern_wx_user_id = wx_user.id and concern.wx_user = lv.wx_user and concern.wx_user is not null
          ) as concern_wx_user_concern_id,
          (
            select id from concern where concern_ic_group = video.ic_group and  concern.wx_user = lv.wx_user and concern.wx_user is not null
          ) as concern_ic_group_concern_id,
          reward_success.unit_price as userRewardPrice,
          video.id_card
      from video
      left join wx_like_video as lv on lv.video_id = video.id and lv.wx_user = ?
      left join wx_user on wx_user.openid = video.wx_user
      left join reward_success on reward_success.video_id = video.id and reward_success.wx_user = ?
      where ${videoSqlText}
    `, videoWhere)


    let answerList = await this.videoRepository.query(`
      select * from (
        select distinct
          b.id,
          b.video_id,
          b.wx_user,
          b.create_time,
          b.check,
          b.check_time,
          b.type,
          b.answer_template_id,
          b.id as answer_id,
          ( select use_wx_user from profit c where c.answer_id = b.id and c.use_wx_user = ?) as use_wx_user,
          e.platform,
          e.ic_name,
          e.img,
          e.img_id ,
          f.status as profit_status,
          b.reject_auto_time
        from answer b
        left join answer_info as e on e.answer_id = b.id
        left join profit as f on f.answer_id = b.id and f.use_wx_user = ?
        inner join (
          select video.id from video
          inner join answer as b on b.video_id = video.id
          where (${videoSqlText}) and b.delete_tag = 0
        ) d on d.id = b.video_id
        where b.delete_tag = 0
      ) as e
      order by e.create_time desc
    `, videoWhere)

    let multiImgList = await this.videoRepository.query(`
      select distinct b.id,b.answer,b.wx_user,b.create_time,b.check,b.check_time,b.type,b.answer_template_id,b.img,b.img_id,b.update_time,c.*,d.img as multi_img,d.video_id
      from multi_img d
      left join answer as b on b.video_id = d.video_id and b.delete_tag = 0
      left join profit as c on c.answer_id = b.id
      where d.video_id in (select video.id from video where ${videoSqlText})
    `, videoWhere.slice(2))

    //查询悬赏金额
    let videoRewardList = []
    videoList.filter(e => e.isreward).map(e => {
      let item = {
        video_id: e.id,
      }
      videoRewardList.push(item)
    })
    if (videoRewardList.length > 0) {
      let rewardList = await this.rewardSuccessRepository.find({ where: videoRewardList })
      this.setRewardPrice(videoList, rewardList)
    }

    return { video: videoList, answer: answerList, multiImg: multiImgList }
  }

  setRewardPrice(videoList, rewardList) {
    videoList.map(e => {
      if (e.isreward) {
        e.isreward = 1
      }
      let findRewardList = rewardList.filter(c => c.video_id == e.id)
      if (findRewardList.length > 0) {
        let list = findRewardList.map(c => Number(c.unit_price))
        let sum = list.reduce(function (prev, cur) {
          return prev + cur;
        }, 0);
        e.rewardPrice = (sum / 100).toFixed(2)
      }
    })
  }


  GetAll_Count(keyword?: string, ic_list?: []): Promise<any> {
    if (ic_list) {
      let where = []
      ic_list.map(e => {
        where.push({
          'ic_group': e
        })
      })
      if (keyword) {
        where.push({
          id: Like(`%${keyword}%`)
        })
      }
      return this.videoRepository.find({
        relations: ['ic_info'],
        where: where
      });
    } else {
      return this.videoRepository.query(`
        select count(1) as total from video
        where id like ?
      `, [`%${keyword || ''}%`])
    }
  }

  async findAll_By_User(skip: number, take: number, ic_list: [], keyword?: string, wx_user?: string, type?: number, notCertified?: boolean, check?: boolean): Promise<{ data: Video[], total: number, multiImg: MultiImg[] }> {
    let where = []
    let params = []
    if (keyword) {
      params.push(keyword)
    }
    ic_list.map(e => {
      if (!isNaN(e)) {
        where.push(`ic_group = ?`)
        params.push(e)
      }
    })
    let whereText = ''
    if (where.length > 0) {
      whereText = `${keyword ? 'and' : ''} (${where.join('or ')})`
    }
    let whereTextStr = `${keyword ? 'v.id = ?' : ''} ${whereText}`
    if (whereTextStr.trim()) {
      whereTextStr = `where ${whereTextStr} and v.source = 2`
    } else {
      whereTextStr = `where v.source = 2`
    }

    if (type !== undefined && !isNaN(type) && type != -1) {
      if (whereTextStr) {
        whereTextStr += ' and v.type = ' + type
      } else {
        whereTextStr += 'where v.type = ' + type
      }
    }
    whereTextStr = (whereTextStr ? whereTextStr + ' and ' : 'where ') + ` v.del_to_in_lib = ${notCertified ? 1 : 0}`

    if (check !== undefined) {
      whereTextStr = (whereTextStr ? whereTextStr + ' and ' : 'where ') + ` v.check = ${check}`
    }
    whereTextStr = (whereTextStr.trim() ? whereTextStr + ' and ' : ' where ') + `
      (
        v.original = 1 or (
          (
            v.original = 0 
            and v.ic_group is not null 
            and v.id not in (
              select video_id from answer
              where answer.wx_user != '${system_wx_user}' and answer.check = 1 and answer.delete_tag = 0
            )
          )
          or (
            v.original = 0 and v.ic_group is null
          )
        )
      )
    `

    let dataList = await this.videoRepository.query(`
      select v.*,
        (select group_concat(id) from video where filemd5 = v.filemd5) as isdistinct,
        (select group_concat(id) from video where ic_group = v.ic_group and ic_group > 0) as isdistinct_ic
      from (
        select v.id,
          v.video_id,
          v.video_cover,
          v.create_time,
          v.update_time,
          v.video_key,
          v.video_ratio,
          v.ic_group,
          v.wx_user,
          v.check,
          v.type,
          v.original,
          v.check_time,
          v.source,
          v.profit_type,
          v.check_text,
          v.check_text_time,
          v.trace_id,
          v.filemd5,
          v.isreward,
          v.overseas,
          v.delete_tag,
          v.id_card,
          v.is_home,
          v.wx_user_source,
          v.in_ic,
          v.ic_group_source,
          v.video_url_source,
          v.video_url,
          v.in_level3,
          v.question_reward_title,
          ic.name as ic_name,reward_success.unit_price,
          (select internet_celebrity.account from internet_celebrity where internet_celebrity.ic_group = v.ic_group and internet_celebrity.account != '' limit 0,1) as account,
          ic.delete_tag as ic_delete_tag,
          (
            select v2.id from video as v2
            inner join platform on platform.ic_group = v2.ic_group
            inner join internet_celebrity_group on internet_celebrity_group.id = v2.ic_group
            where v2.id = v.id and internet_celebrity_group.type = 0
              and (
                platform.platform in (select setting.value from setting where setting.key = 'level3')
                or (select count(1) from platform where platform.platform != '' and platform.ic_group = internet_celebrity_group.id) = 0
              )
              and v2.type = 0
            limit 0,1
          ) as otherNetwork_ic_info,
          (
            select v2.id from video as v2
            inner join platform on platform.ic_group = v2.ic_group
            inner join internet_celebrity_group on internet_celebrity_group.id = v2.ic_group
            where v2.id = v.id and internet_celebrity_group.type = 0
              and (
                platform.platform in (select setting.value from setting where setting.key = 'level3')
                or (select count(1) from platform where platform.platform != '' and platform.ic_group = internet_celebrity_group.id) = 0
              )
              and v2.type = 1
            limit 0,1
          ) as otherNetwork_ic_info_img,
          (
            select v2.id from video as v2
            inner join platform on platform.ic_group = v2.ic_group
            inner join internet_celebrity_group on internet_celebrity_group.id = v2.ic_group
            where v2.id = v.id and v2.in_level3 = 0 and (v2.source = 2 or v2.source = 0 or v2.original = 0) and v2.ic_group is not null
              and v2.id not in (
                select video.id from video
                where video.check = 1 and (video.source = 2 or v2.source = 0 or video.original = 0) and (
                  video.ic_group in (
                    select a.id from (
                      select distinct internet_celebrity_group.id from internet_celebrity_group 
                      left join platform on platform.ic_group = internet_celebrity_group.id
                      inner join video on video.ic_group = internet_celebrity_group.id
                      where (
                        (
                          internet_celebrity_group.type = 2 
                        )
                        or(
                          internet_celebrity_group.type = 0 and (
                            platform.platform in (select setting.value from setting where setting.key = 'level3')
                            or (select count(1) from platform where platform.platform != '' and platform.ic_group = internet_celebrity_group.id) = 0
                          )
                        )
                        or (
                          internet_celebrity_group.type = 3 
                        )
                      )
                    ) a
                  )
                  or ((video.overseas = 3 or video.overseas = 1) and video.original = 1)
                )
              )
            limit 0,1
          ) as is_lib,
          (select count(1) from platform where platform.platform = '微博' and platform.ic_group = v.ic_group) as iswb
        from video v
        left join internet_celebrity_group ic on ic.id = v.ic_group
        left join reward_success on reward_success.video_id = v.id and reward_success.wx_user = ?
        ${whereTextStr}
        order by v.id desc
        limit ?,?
      ) v
    `, [wx_user, ...params, skip, take])
    // dataList.map(e => {
    //   if(e.video_url_source){
    //     e.video_url = e.video_url_source
    //   }
    // })
    //查询ic_list
    let ic_where = []
    let ic_where_obj = {}
    dataList.map(e => {
      if (e.ic_group) {
        if (!ic_where_obj[e.ic_group]) {
          ic_where_obj[e.ic_group] = true
          ic_where.push({ ic_group: e.ic_group })
        }
      }
      if (e.ic_name) {
        e.ic_info = { name: e.ic_name, account: e.account }
      }
    })
    let icList: any = []
    if (ic_where.length > 0) {
      icList = await this.icRepository.find({
        where: ic_where
      })
    }
    icList.map(e => {
      dataList.filter(c => c.ic_group == e.ic_group).map((c: any) => {
        c.ic_list = c.ic_list || []
        c.ic_list.push(e)
      })
    })
    let total = await this.videoRepository.query(`
      select count(1) as total
      from video v
      ${whereTextStr}
    `, params)

    total = Number(total[0].total)

    //tags
    let videoIDS = dataList.map(e => e.id)
    let tagWhere = '1 = 1'
    let tagWhereParams: any = {}
    if (videoIDS.length > 0) {
      tagWhere = 'video_id IN (:...ids)'
      tagWhereParams.ids = videoIDS
    }
    let tags = await this.videoTagRepository
      .createQueryBuilder("video_tag")
      .innerJoin("tags", "b", 'b.id = video_tag.tag_id')
      .innerJoin("tags", "c", 'c.id = b.parentId')
      .select(`
        video_tag.tag_id,
        video_tag.id,
        video_tag.video_id, 
        b.tag,
        c.tag parentTag,
        b.parentId
      `)
      .where(tagWhere, tagWhereParams)
      .printSql()
      .getRawMany()
    dataList.map((e: any) => {
      e.tags = tags.filter(c => c.video_id == e.id)
    })

    const whereMulti = []
    dataList.map(e => {
      whereMulti.push({ video_id: e.id })
    })
    let multi_img: any = []
    if (whereMulti.length > 0) {
      multi_img = await this.multiImgRepository.find({
        where: whereMulti
      })
    }
    return {
      data: dataList,
      total: total,
      multiImg: multi_img
    }
  }

  async findAll_By_User_Abroad(skip: number, take: number, ic_list: [], keyword?: string, wx_user?: string, type?: number, notCertified?: boolean, check?: boolean): Promise<{ data: Video[], total: number, multiImg: MultiImg[] }> {
    let where = []
    let params = []
    if (keyword) {
      params.push(keyword)
    }
    ic_list.map(e => {
      if (!isNaN(e)) {
        where.push(`ic_group = ?`)
        params.push(e)
      }
    })
    let whereText = ''
    if (where.length > 0) {
      whereText = `${keyword ? 'and' : ''} (${where.join('or ')})`
    }
    let whereTextStr = `${keyword ? 'v.id = ?' : ''} ${whereText}`
    if (whereTextStr.trim()) {
      whereTextStr = `where ${whereTextStr} and v.source = 2`
    } else {
      whereTextStr = `where v.source = 2`
    }

    if (type !== undefined && !isNaN(type) && type != -1) {
      if (whereTextStr) {
        whereTextStr += ' and v.type = ' + type
      } else {
        whereTextStr += 'where v.type = ' + type
      }
    }

    if (check !== undefined) {
      whereTextStr = (whereTextStr ? whereTextStr + ' and ' : 'where ') + ` v.check = ${check}`
    }
    whereTextStr = (whereTextStr.trim() ? whereTextStr + ' and ' : ' where ') + `
      (
        v.original = 1 or (
          (
            v.original = 0 
            and v.ic_group is not null 
            and v.id not in (
              select video_id from answer
              where answer.wx_user != '${system_wx_user}' and answer.check = 1 and answer.delete_tag = 0
            )
          )
          or (
            v.original = 0 and v.ic_group is null
          )
        )
      )
    `

    let dataList = await this.videoRepository.query(`
      select v.*,
        (select group_concat(id) from video where filemd5 = v.filemd5) as isdistinct,
        (select group_concat(id) from video where ic_group = v.ic_group and ic_group > 0) as isdistinct_ic
      from (
        select v.id,
          v.video_id,
          v.video_cover,
          v.create_time,
          v.update_time,
          v.video_key,
          v.video_ratio,
          v.ic_group,
          v.wx_user,
          v.check,
          v.type,
          v.original,
          v.check_time,
          v.source,
          v.profit_type,
          v.check_text,
          v.check_text_time,
          v.trace_id,
          v.filemd5,
          v.isreward,
          v.overseas,
          v.delete_tag,
          v.id_card,
          v.is_home,
          v.wx_user_source,
          v.in_ic,
          v.ic_group_source,
          v.video_url_source,
          v.video_url,
          v.in_level3,
          v.question_reward_title,
          ic.name as ic_name,reward_success.unit_price,
          (select internet_celebrity.account from internet_celebrity where internet_celebrity.ic_group = v.ic_group and internet_celebrity.account != '' limit 0,1) as account,
          ic.delete_tag as ic_delete_tag,
          (
            select v2.id from video as v2
            inner join platform on platform.ic_group = v2.ic_group
            inner join internet_celebrity_group on internet_celebrity_group.id = v2.ic_group
            where v2.id = v.id and internet_celebrity_group.type = 0
              and (
                platform.platform in (select setting.value from setting where setting.key = 'level3')
                or (select count(1) from platform where platform.platform != '' and platform.ic_group = internet_celebrity_group.id) = 0
              )
              and v2.type = 0
            limit 0,1
          ) as otherNetwork_ic_info,
          (
            select v2.id from video as v2
            inner join platform on platform.ic_group = v2.ic_group
            inner join internet_celebrity_group on internet_celebrity_group.id = v2.ic_group
            where v2.id = v.id and internet_celebrity_group.type = 0
              and (
                platform.platform in (select setting.value from setting where setting.key = 'level3')
                or (select count(1) from platform where platform.platform != '' and platform.ic_group = internet_celebrity_group.id) = 0
              )
              and v2.type = 1
            limit 0,1
          ) as otherNetwork_ic_info_img,
          (
            select v2.id from video as v2
            inner join platform on platform.ic_group = v2.ic_group
            inner join internet_celebrity_group on internet_celebrity_group.id = v2.ic_group
            where v2.id = v.id and v2.in_level3 = 0 and (v2.source = 2 or v2.source = 0 or v2.original = 0) and v2.ic_group is not null
              and v2.id not in (
                select video.id from video
                where video.check = 1 and (video.source = 2 or v2.source = 0 or video.original = 0) and (
                  video.ic_group in (
                    select a.id from (
                      select distinct internet_celebrity_group.id from internet_celebrity_group 
                      left join platform on platform.ic_group = internet_celebrity_group.id
                      inner join video on video.ic_group = internet_celebrity_group.id
                      where (
                        (
                          internet_celebrity_group.type = 2 
                        )
                        or(
                          internet_celebrity_group.type = 0 and (
                            platform.platform in (select setting.value from setting where setting.key = 'level3')
                            or (select count(1) from platform where platform.platform != '' and platform.ic_group = internet_celebrity_group.id) = 0
                          )
                        )
                        or (
                          internet_celebrity_group.type = 3 
                        )
                      )
                    ) a
                  )
                  or ((video.overseas = 3 or video.overseas = 1) and video.original = 1)
                )
              )
            limit 0,1
          ) as is_lib
        from video_abroad v
        left join internet_celebrity_group ic on ic.id = v.ic_group
        left join reward_success on reward_success.video_id = v.id and reward_success.wx_user = ?
        ${whereTextStr}
        order by v.id desc
        limit ?,?
      ) v
    `, [wx_user, ...params, skip, take])
    // dataList.map(e => {
    //   if(e.video_url_source){
    //     e.video_url = e.video_url_source
    //   }
    // })
    //查询ic_list
    let ic_where = []
    let ic_where_obj = {}
    dataList.map(e => {
      if (e.ic_group) {
        if (!ic_where_obj[e.ic_group]) {
          ic_where_obj[e.ic_group] = true
          ic_where.push({ ic_group: e.ic_group })
        }
      }
      if (e.ic_name) {
        e.ic_info = { name: e.ic_name, account: e.account }
      }
    })
    let icList: any = []
    if (ic_where.length > 0) {
      icList = await this.icRepository.find({
        where: ic_where
      })
    }
    icList.map(e => {
      dataList.filter(c => c.ic_group == e.ic_group).map((c: any) => {
        c.ic_list = c.ic_list || []
        c.ic_list.push(e)
      })
    })
    let total = await this.videoRepository.query(`
      select count(1) as total
      from video_abroad v
      ${whereTextStr}
    `, params)

    total = Number(total[0].total)

    //tags
    let videoIDS = dataList.map(e => e.id)
    let tagWhere = '1 = 1'
    let tagWhereParams: any = {}
    if (videoIDS.length > 0) {
      tagWhere = 'video_id IN (:...ids)'
      tagWhereParams.ids = videoIDS
    }
    let tags = await this.videoTagRepository
      .createQueryBuilder("video_tag")
      .innerJoin("tags", "b", 'b.id = video_tag.tag_id')
      .innerJoin("tags", "c", 'c.id = b.parentId')
      .select(`
        video_tag.tag_id,
        video_tag.id,
        video_tag.video_id, 
        b.tag,
        c.tag parentTag,
        b.parentId
      `)
      .where(tagWhere, tagWhereParams)
      .printSql()
      .getRawMany()
    dataList.map((e: any) => {
      e.tags = tags.filter(c => c.video_id == e.id)
    })

    const whereMulti = []
    dataList.map(e => {
      whereMulti.push({ video_id: e.id })
    })
    let multi_img: any = []
    if (whereMulti.length > 0) {
      multi_img = await this.multiImgRepository.find({
        where: whereMulti
      })
    }
    return {
      data: dataList,
      total: total,
      multiImg: multi_img
    }
  }

  /**
   * 获取审核脚本
   * @param mediaCheckType 
   * @returns 
   */
  getMediaCheck_Sql(mediaCheckType: number) {
    let mediaCheckWhere = ''
    switch (mediaCheckType) {
      case 1://审核通过
        mediaCheckWhere = ` and ((c.suggest = 'pass' or video.type = 0) or (video.type = 1 and video.id not in (
          select a.video_id from multi_img a
          inner join media_check b on b.trace_id = a.trace_id
          where a.video_id = video.id and b.suggest != 'pass'
        )) or video.trace_id is null)`
        break;
      case 2://不通过
        mediaCheckWhere = ` and (c.suggest = 'risky' or c.suggest = 'review' or (video.type = 1 and video.id in (
          select a.video_id from multi_img a
          inner join media_check b on b.trace_id = a.trace_id
          where a.video_id = video.id and b.suggest != 'pass'
        )))`
        break;
      case 0:
        mediaCheckWhere = " and ((c.id is null and video.type = 1 and video.trace_id is not null))"
        break;
    }
    return mediaCheckWhere
  }

  /**
   * 获取审核脚本
   * @param mediaCheckType 
   * @returns 
   */
  getCheckText_Sql(check_text: number) {
    let checkTextWere = ''
    switch (check_text) {
      case 1://审核通过
        checkTextWere = ` and video.check_text = 1`
        break;
      case 2://不通过
        checkTextWere = ` and video.check_text = 0`
        break;
      case 0:
        checkTextWere = " and video.check_text is null"
        break;
    }
    return checkTextWere
  }

  gerIsAnswerSql(isAnswer) {
    let isAnswerSql = ''
    switch (isAnswer) {
      case 'yes':
        isAnswerSql = `
          and (video.id in (
            select video_id from answer where answer.check = 1
          ) and video.check = 1)
        `
        break;
      case 'no':
        isAnswerSql = `
          and (video.id not in (
            select video_id from answer where answer.check = 1
          ) or video.check = 0)
        `
        break;
    }
    return isAnswerSql
  }

  async findAll(skip: number, take: number, keyword?: string, mediaCheckType?: number, isAnswer?: string): Promise<any> {
    const mediaCheckWhere = this.getMediaCheck_Sql(mediaCheckType)
    let isAnswerSql = this.gerIsAnswerSql(isAnswer)
    const videoList = await this.videoRepository.query(`
      select video.id as id,
        video.video_id as video_id,
        video.video_url as video_url,
        video.video_url_source as video_url_source,
        video.video_cover as video_cover,
        video.video_key as video_key,
        video.video_ratio as video_ratio,
        video.ic_group as ic_group,
        video.original,
        b.name as ic_name,
        b.delete_tag as ic_delete_tag,
        video.type,
        video.check,
        video.profit_type,
        video.check_text,
        video.trace_id,
        video.is_home,
        video.in_ic,
        (
          select v.id from video as v
          inner join platform on platform.ic_group = v.ic_group
          inner join internet_celebrity_group on internet_celebrity_group.id = v.ic_group
          where v.id = video.id and internet_celebrity_group.type = 0
            and platform.platform in (select setting.value from setting where setting.key = 'level3')
            and internet_celebrity_group.delete_tag = 0
            and (
              v.overseas = 3
              or (v.original = 0 and v.type = 0)
            )
            
          limit 0,1
        ) as otherNetwork_ic_info,
        case when c.suggest = 'pass' then
        (
          select suggest from media_check a
          inner join multi_img b on b.trace_id = a.trace_id
          where b.video_id = video.id and a.suggest != 'pass'
        ) else c.suggest end suggest,
        c.label,
        c.prob,
        (select count(1) total from profit p inner join answer a on a.id = p.answer_id and a.delete_tag = 0 where a.video_id = video.id and p.status = 3) as refund_count
      from video
      left join internet_celebrity_group b on b.id = video.ic_group and b.is_init != 1
      left join media_check c on c.trace_id = video.trace_id
      where ${isFindRobot} video.id like ? ${mediaCheckWhere} ${isAnswerSql}
      order by video.create_time desc
      limit ?,?
    `, [`%${keyword}%`, skip, take])

    videoList.map(e => {
      if (e.video_url_source) {
        e.video_url = e.video_url_source
      }
    })

    const multi_img = await this.videoRepository.query(`
      select a.video_id,a.img
      from multi_img a
      inner join (
        select video.id from video
        left join media_check c on c.trace_id = video.trace_id
        where ${isFindRobot} video.id like ? ${mediaCheckWhere} ${isAnswerSql}
        order by video.create_time desc
        limit ?,?
      ) b on b.id = a.video_id
    `, [`%${keyword}%`, skip, take])

    const total = await this.videoRepository.query(`
        select count(1) as total from video
        left join media_check c on c.trace_id = video.trace_id
        where ${isFindRobot} video.id like ? ${mediaCheckWhere} ${isAnswerSql}
      `, [`%${keyword || ''}%`])
    return { video: videoList, multiImg: multi_img, total: Number(total[0].total) }
  }
  /**
   * 作品
   * @param skip 
   * @param take 
   * @param keyword 
   * @returns 
   */
  async findAll_Original(skip: number, take: number, keyword?: string, mediaCheckType?: number, isAnswer?: string, notauth?: boolean): Promise<any> {
    const mediaCheckWhere = this.getCheckText_Sql(mediaCheckType)
    let noauthWhere = ` and ${notauth ? ' video.overseas = 3' : ' video.overseas = 1'}`
    keyword = keyword || ''
    const videoList = await this.videoRepository.query(`
      select video.id as id,
        video.video_id as video_id,
        video.video_url as video_url,
        video.video_url_source as video_url_source,
        video.video_cover as video_cover,
        video.video_key as video_key,
        video.video_ratio as video_ratio,
        video.ic_group as ic_group,
        video.original,
        b.name as ic_name,
        b.delete_tag as ic_delete_tag,
        video.type,
        video.check,
        video.profit_type,
        video.check_text,
        video.trace_id,
        video.is_home,
        video.in_ic,
        (
          select v.id from video as v
          inner join platform on platform.ic_group = v.ic_group
          inner join internet_celebrity_group on internet_celebrity_group.id = v.ic_group
          where v.id = video.id and (
            (
              internet_celebrity_group.type = 0
              and platform.platform in (select setting.value from setting where setting.key = 'level3')
              and internet_celebrity_group.delete_tag = 0
              and v.type = 0
            )
            or (
              v.overseas = 3 and v.profit_type = 1
            )
          )
          limit 0,1
        ) as otherNetwork_ic_info,
        case when c.suggest = 'pass' then
        (
          select suggest from media_check a
          inner join multi_img b on b.trace_id = a.trace_id
          where b.video_id = video.id and a.suggest != 'pass'
        ) else c.suggest end suggest,
        c.label,
        c.prob,
        (select count(1) total from profit p inner join answer a on a.id = p.answer_id and a.delete_tag = 0 where a.video_id = video.id and p.status = 3) as refund_count
      from video
      left join internet_celebrity_group b on b.id = video.ic_group and b.is_init != 1
      left join media_check c on c.trace_id = video.trace_id
      where ${isFindRobot} video.original = 1 and (video.id = ? or ? = '') ${mediaCheckWhere} ${noauthWhere}
      order by video.create_time asc
      limit ?,?
    `, [keyword, keyword, skip, take])

    let answerList = []
    //查询视频关联的网红
    let videoRelaIcWhere = []
    videoList.map(e => {
      if (e.video_url_source) {
        e.video_url = e.video_url_source
      }
      e.answerList = []
      videoRelaIcWhere.push(`video.id = ?`)
    })
    if (videoRelaIcWhere.length > 0) {
      let videoRelaIc = await this.videoRepository.query(`
        select distinct platform.platform,internet_celebrity.name as ic_name, internet_celebrity.account, internet_celebrity.img, internet_celebrity.avatar_img,video.id,
          wx_user.id_card as wx_user_id_card,wx_user.name as wx_user_name
        from internet_celebrity
        inner join platform on platform.id = internet_celebrity.platform
        inner join video on video.ic_group = internet_celebrity.ic_group
        inner join wx_user on wx_user.openid = video.wx_user
        where (${videoRelaIcWhere.join(' or ')}) and platform.platform is not null and platform.platform != ''
      `, videoList.map(e => e.id))

      //查询没有关联网红的答案
      let videoNotRelaAnswer = await this.videoRepository.query(`
        select distinct answer_info.platform,answer_info.ic_name,answer_info.account,answer_info.img,answer_info.avatar_img,video.id,answer_info.answer_id as answer_id
        from answer_info
        inner join video on video.id = answer_info.video_id and video.ic_group is null
        where (${videoRelaIcWhere.join(' or ')}) and answer_info.platform is not null and answer_info.platform != ''
      `, videoList.map(e => e.id))

      videoRelaIc.map((e, index) => {
        let findVideo = videoList.find(c => c.id == e.id)
        if (findVideo) {
          if (!findVideo.ic_info) {
            findVideo.ic_info = e
          } else {
            let addVideo = JSON.parse(JSON.stringify(findVideo))
            addVideo.ic_info = e
            videoList.push(addVideo)
          }
        }
      })
      videoNotRelaAnswer.map((e, index) => {
        let findVideo = videoList.find(c => c.id == e.id)
        if (findVideo) {
          if (!findVideo.ic_info) {
            findVideo.ic_info = e
            findVideo.answer_id = e.answer_id
          } else {
            let addVideo = JSON.parse(JSON.stringify(findVideo))
            addVideo.ic_info = e
            addVideo.answer_id = e.answer_id
            videoList.push(addVideo)
          }
        }
      })
    }

    let whereSql = []
    videoList.map(e => {
      whereSql.push(` video.id = ? `)
    })
    let multi_img: any = []
    if (whereSql.length > 0) {
      multi_img = await this.videoRepository.query(`
        select a.video_id,a.img
        from multi_img a
        inner join (
          select video.id from video
          left join media_check c on c.trace_id = video.trace_id
          where ${isFindRobot} video.original = 1 and (video.id = ? or ? = '') ${mediaCheckWhere} and (${whereSql.join(' or ')})
          order by video.create_time desc
        ) b on b.id = a.video_id
      `, [keyword, keyword, ...videoList.map(e => e.id)])
    }

    const total = await this.videoRepository.query(`
      select count(1) total
      from video
      left join media_check c on c.trace_id = video.trace_id
      where ${isFindRobot} video.original = 1 and (video.id = ? or ? = '') ${mediaCheckWhere} ${noauthWhere}
    `, [keyword, keyword])
    return { video: videoList, multiImg: multi_img, total: Number(total[0].total) }
  }

  //提问
  async findAll_Question(skip: number, take: number, keyword?: string, mediaCheckType?: number, isAnswer?: string): Promise<any> {
    const mediaCheckWhere = this.getCheckText_Sql(mediaCheckType)
    keyword = keyword || ''
    let dataList = await this.videoRepository.query(`
      select video.*,
      video.in_ic,
      b.name as ic_name,
        (
          select v.id from video as v
          inner join platform on platform.ic_group = v.ic_group
          inner join internet_celebrity_group on internet_celebrity_group.id = v.ic_group
          where v.id = video.id and internet_celebrity_group.type = 0
            and platform.platform in (select setting.value from setting where setting.key = 'level3')
            and internet_celebrity_group.delete_tag = 0
            and (
              v.overseas = 3
              or (v.original = 0 and v.type = 0)
            )
            
          limit 0,1
        ) as otherNetwork_ic_info,
      case when c.suggest = 'pass' then
      (
        select suggest from media_check a
        inner join multi_img b on b.trace_id = a.trace_id
        where b.video_id = video.id and a.suggest != 'pass'
      ) else c.suggest end suggest,
      c.label,
      c.prob,
      (select count(1) total from profit p inner join answer a on a.id = p.answer_id and a.delete_tag = 0 where a.video_id = video.id and p.status = 3) as refund_count
      from video
      left join media_check c on c.trace_id = video.trace_id
      left join internet_celebrity_group b on b.id = video.ic_group and b.is_init != 1
      where ${isFindRobot} video.original = 0 and (video.id = ? or '' = ?)
         ${mediaCheckWhere}
      order by video.create_time asc
      limit ?,?
    `, [keyword, keyword, skip, take])

    //查询视频关联的网红
    let videoRelaIcWhere = []
    dataList.map(e => {
      if (e.video_url_source) {
        e.video_url = e.video_url_source
      }
      videoRelaIcWhere.push(`video.id = ?`)
    })

    if (videoRelaIcWhere.length > 0) {
      let videoRelaIc = await this.videoRepository.query(`
        select distinct platform.platform,internet_celebrity.name as ic_name, internet_celebrity.account, internet_celebrity.img, internet_celebrity.avatar_img,video.id
        from internet_celebrity
        inner join platform on platform.id = internet_celebrity.platform
        inner join video on video.ic_group = internet_celebrity.ic_group
        where (${videoRelaIcWhere.join(' or ')}) and platform.platform is not null and platform.platform != ''
      `, dataList.map(e => e.id))

      videoRelaIc.map((e, index) => {
        let findVideo = dataList.find(c => c.id == e.id)
        if (findVideo) {
          if (!findVideo.ic_info) {
            findVideo.ic_info = e
          } else {
            let addVideo = JSON.parse(JSON.stringify(findVideo))
            addVideo.ic_info = e
            dataList.push(addVideo)
          }
        }
      })
    }

    const multi_img = await this.videoRepository.query(`
      select a.video_id,a.img
      from multi_img a
      inner join (
        select video.id from video
        left join media_check c on c.trace_id = video.trace_id
        left join reward reward on reward.video_id = video.id
        where ${isFindRobot} video.original = 0 and (video.id = ? or '' = ?) ${mediaCheckWhere}
        order by video.create_time desc
        limit ?,?
      ) b on b.id = a.video_id
    `, [keyword, keyword, skip, take])

    let total = await this.videoRepository.query(`
      select count(1) as total from video
      left join media_check c on c.trace_id = video.trace_id
      left join internet_celebrity_group b on b.id = video.ic_group and b.is_init != 1
      where ${isFindRobot} video.original = 0 and (video.id = ? or '' = ?)
         ${mediaCheckWhere}
    `, [keyword, keyword])

    return { video: dataList, total: Number(total[0].total), multiImg: multi_img }
  }


  //回答
  async findAll_Answer(skip: number, take: number, keyword?: string, mediaCheckType?: number, isAnswer?: string): Promise<any> {
    const mediaCheckWhere = this.getMediaCheck_Sql(mediaCheckType)
    let isAnswerSql = this.gerIsAnswerSql(isAnswer)
    let dataList = await this.videoRepository.query(`
      select distinct video.*,
        video.in_ic,
        (
          select v.id from video as v
          inner join platform on platform.ic_group = v.ic_group
          inner join internet_celebrity_group on internet_celebrity_group.id = v.ic_group
          where v.id = video.id and internet_celebrity_group.type = 0
            and platform.platform in (select setting.value from setting where setting.key = 'level3')
            and internet_celebrity_group.delete_tag = 0
            and (
              v.overseas = 3
              or (v.original = 0 and v.type = 0)
            )
            
          limit 0,1
        ) as otherNetwork_ic_info,
        (
          select count(1) from profit b
          where b.answer_id = c.id
        ) as profit_count,
      case when c.suggest = 'pass' then
      (
        select suggest from media_check a
        inner join multi_img b on b.trace_id = a.trace_id
        where b.video_id = video.id and a.suggest != 'pass'
      ) else c.suggest end suggest,
      c.label,
      c.prob,
      (select count(1) total from profit p inner join answer a on a.id = p.answer_id and a.delete_tag = 0 where a.video_id = video.id and p.status = 3) as refund_count
      from video
      inner join answer b on b.video_id = video.id and b.delete_tag = 0
      left join media_check c on c.trace_id = video.trace_id
      where ${isFindRobot} video.id like ? and b.wx_user != video.wx_user ${mediaCheckWhere} ${isAnswerSql}
      order by video.create_time desc
      limit ?,?
    `, [`%${keyword || ''}%`, skip, take])

    dataList.map(e => {
      if (e.video_url_source) {
        e.video_url = e.video_url_source
      }
    })

    const multi_img = await this.videoRepository.query(`
      select a.video_id,a.img
      from multi_img a
      inner join (
        select video.id from video
        inner join answer b on b.video_id = video.id and b.delete_tag = 0
        left join media_check c on c.trace_id = video.trace_id
        where ${isFindRobot} video.id like ? and b.wx_user != video.wx_user ${mediaCheckWhere} ${isAnswerSql}
        order by video.create_time desc
        limit ?,?
      ) b on b.id = a.video_id
    `, [`%${keyword || ''}%`, skip, take])

    let total = await this.videoRepository.query(`
      select count(1) as total
      from video
      inner join answer b on b.video_id = video.id and b.delete_tag = 0
      left join media_check c on c.trace_id = video.trace_id
      where ${isFindRobot} video.id like ? and b.wx_user != video.wx_user ${mediaCheckWhere} ${isAnswerSql}
    `, [`%${keyword || ''}%`])
    return { video: dataList, total: Number(total[0].total), multiImg: multi_img }
  }


  /**
   * 查询最后一个视频
   */
  async findUserLastVideo(wx_user?: string, loadType?: string): Promise<{ video: [], answer: [], multiImg: [] }> {
    let loadTypeWhere: string = ''
    if (loadType != 'all') {
      loadTypeWhere = `and video.type = '${loadType == 'image' ? 1 : 0}'`
    }

    let lastVideoId = await this.watchRecordRepository.query(`
      select watch_record.* from watch_record
      inner join video on video.id = watch_record.video_id
      where watch_record.wx_user = ? ${loadTypeWhere} and video.delete_tag = 0
      order by id desc
      limit 0,1
    `, [wx_user])
    if (lastVideoId.length === 0) {
      return { video: [], answer: [], multiImg: [] }
    }
    let { sql, beforeParams, afterParams } = this.getQueryVideoField(wx_user, `
      (
        select *
        from video
        where video.id = ?
      ) video
    `)
    let videoList = await this.videoRepository.query(`
      select 
        ${sql}
    `, [...beforeParams, lastVideoId[0].video_id, ...afterParams])

    videoList.map(e => {
      if (e.otherNetwork_ic_info || e.authen_work || e.otherNetwork) {
        e.workSource = 'ic'
      } else if (e.ic_group) {
        e.workSource = 'lib'
      } else {
        e.workSource = 'question'
      }
    })

    let { answerList, multiImg } = await this.getVideoOtherParams(lastVideoId.map(e => e.video_id), lastVideoId.map(e => e.video_id), wx_user)


    //查询悬赏金额
    let videoRewardList = []
    videoList.filter(e => e.isreward).map(e => {
      let item = {
        video_id: e.id,
      }
      videoRewardList.push(item)
    })
    if (videoRewardList.length > 0) {
      let rewardList = await this.rewardSuccessRepository.find({ where: videoRewardList })
      this.setRewardPrice(videoList, rewardList)
    }

    return { video: videoList, answer: answerList, multiImg: multiImg }
  }

  async GetVideoCount(pageSize: number, loadType: string) {
    //视频库上传
    let isLibTotal = 1
    //网红自己的作品
    let isIcTotal = 1
    //普通用户的提问
    let isQuestionTotal = 1
    //视频
    let videoCount = await this.settingRepository.findOne({ where: { key: 'push_count_video' } })
    let videoCountTotal = parseInt(videoCount.value)
    //图片
    let imageCount = await this.settingRepository.findOne({ where: { key: 'push_count_image' } })
    let imageCountTotal = parseInt(imageCount.value)


    if (loadType === 'video') {
      imageCountTotal = 0
    } else if (loadType === 'image') {
      videoCountTotal = 0
    }

    //获取最小公倍数
    let lcm = utils.LCM(isLibTotal + isIcTotal + isQuestionTotal, videoCountTotal + imageCountTotal)
    lcm = utils.LCM(lcm, pageSize)

    let arr = []
    let isLibTotalTemp = isLibTotal
    let isIcTotalTemp = isIcTotal
    let isQuestionTotalTemp = isQuestionTotal

    for (let i = 0; i < lcm; i++) {
      let item: any = {}
      if (isQuestionTotalTemp > 0) {
        item.type = 'question' //1
        isQuestionTotalTemp--
      } else if (isLibTotalTemp > 0) {
        item.type = 'lib'//2
        isLibTotalTemp--
      } else if (isIcTotalTemp > 0) {
        item.type = 'ic'//3
        isIcTotalTemp--
      }
      arr.push(item)
      if (isLibTotalTemp === 0 && isIcTotalTemp === 0 && isQuestionTotalTemp === 0) {
        isLibTotalTemp = isLibTotal
        isIcTotalTemp = isIcTotal
        isQuestionTotalTemp = isQuestionTotal
      }
    }

    let videoCountTotalTemp = videoCountTotal, imageCountTotalTemp = imageCountTotal
    arr.map(e => {
      if (videoCountTotalTemp > 0) {
        videoCountTotalTemp--
        e.workType = 'video'
      } else {
        imageCountTotalTemp--
        e.workType = 'image'
      }
      if (videoCountTotalTemp === 0 && imageCountTotalTemp === 0) {
        videoCountTotalTemp = videoCountTotal
        imageCountTotalTemp = imageCountTotal
      }
    })
    return { arr, lcm }
  }

  generateSql_Lib(wx_user, removeSql, removeSql_Ic, removeIds, removeIcs, imageScale) {
    let list = []
    let paramsList = []
    let getRandom = () => {
      let number = Math.random() * 100
      if (number <= imageScale) {
        return 1
      } else {
        return 0
      }
    }
    let generateSql = (rand: number, count: number, i: number) => {
      let querySql = `
        select * from 
        (
          select 'level${i}' as genrand,video.*,
            (
              select questions.post_answer from questions
              where questions.wx_user = ? and questions.video_id = video.id
            ) as post_answer
          from video
          where video.id in (
            select max(video.id) as id
            from video
            where video.check = 1 and video.source = 2 and video.delete_tag = 0 and video.ic_group is not null and video.is_home = 1
            and video.ic_group not in (
              select watch_record_ic.ic_group from watch_record_ic
              where watch_record_ic.wx_user = ?
            )
            and video.id not in (
              select video.id from video
              where video.check = 1 and video.source = 2 and (
                video.ic_group in (
                  select a.id from (
                    select distinct internet_celebrity_group.id from internet_celebrity_group 
                    left join platform on platform.ic_group = internet_celebrity_group.id
                    inner join video on video.ic_group = internet_celebrity_group.id
                    where (
                      (
                        internet_celebrity_group.type = 2 
                      )
                      or(
                        internet_celebrity_group.type = 0 and platform.platform in (select setting.value from setting where setting.key = 'level3')
                      )
                      or (
                        internet_celebrity_group.type = 3 
                      )
                    )
                  ) a
                )
                or ((video.overseas = 3 or video.overseas = 1) and video.original = 1)
              )
            )
            and video.id not in (
              select watch_record.video_id from watch_record
              where watch_record.wx_user = ?
            )
            and video.id not in (
              select video_id from reward_success
              where reward_success.unit_price = 20000
            )
            ${removeSql} ${removeSql_Ic}
            group by video.ic_group
          )
          and video.type = ?
          order by video.create_time desc
          limit 0,${count}
        ) video
      `
      paramsList.push(...[wx_user, wx_user, wx_user, ...removeIds, ...removeIcs, getRandom()])
      return querySql
    }
    for (let i = 0; i < 3; i++) {
      let rand = parseInt((Math.random() * 100).toString())
      let count = 1
      if (i === 1) {
        count = 2
      } else if (i === 2) {
        count = 4
      }
      list.push(generateSql(rand, count, i + 1))
    }

    let sql = `(
      select video.* from (
        ${list.join(' union ')}
      ) video
    ) video`
    return { sql, paramsList }
  }

  /**
   * 视频库视频
   * @param skip 
   * @param take 
   * @param wx_user 
   * @returns 
   */
  findAll_LibWorks(skip: number, take: number, wx_user: string, workType: number, removeIds: [], removeIcs: [], imageScale?: number) {
    let removeSql: any = []
    removeIds = removeIds || []
    removeIds.map(e => {
      removeSql.push(`video.id != ?`)
    })
    if (removeSql.length > 0) {
      removeSql = ` and (${removeSql.join(' and ')})`
    } else {
      removeSql = ''
    }
    let removeSql_Ic: any = []
    removeIcs = removeIcs || []
    removeIcs.map(e => {
      removeSql_Ic.push(`video.ic_group != ?`)
    })
    if (removeSql_Ic.length > 0) {
      removeSql_Ic = ` and (${removeSql_Ic.join(' and ')})`
    } else {
      removeSql_Ic = ''
    }

    let querySql = `
      (
        select *,
          (
            select questions.post_answer from questions
            where questions.wx_user = ? and questions.video_id = video.id
          ) as post_answer
        from video
        where video.id in (
            select max(video.id) as id
            from video
            where video.check = 1 and video.source = 2 and video.delete_tag = 0 and video.ic_group is not null and video.is_home = 1
            and video.id not in (
              select video.id from video
              where video.check = 1 and video.source = 2 and (
                video.ic_group in (
                  select a.id from (
                    select distinct internet_celebrity_group.id from internet_celebrity_group 
                    left join platform on platform.ic_group = internet_celebrity_group.id
                    inner join video on video.ic_group = internet_celebrity_group.id
                    where (
                      (
                        internet_celebrity_group.type = 2 
                      )
                      or(
                        internet_celebrity_group.type = 0 and platform.platform in (select setting.value from setting where setting.key = 'level3')
                      )
                      or (
                        internet_celebrity_group.type = 3 
                      )
                    )
                  ) a
                )
                or ((video.overseas = 3 or video.overseas = 1) and video.original = 1)
              )
            )
            and video.ic_group not in (
              select watch_record_ic.ic_group from watch_record_ic
              where watch_record_ic.wx_user = ?
            )
            and video.id not in (
              select watch_record.video_id from watch_record
              where watch_record.wx_user = ?
            )
            and video.id not in (
              select video_id from reward_success
              where reward_success.unit_price = 20000
            )
            ${workType !== undefined ? ` and (video.type = ? or ? = -1)` : ''}
            ${removeSql} ${removeSql_Ic}
            group by video.ic_group    
        )
      ) video
    `
    let paramsList: any = [wx_user, wx_user, wx_user, ...removeIds, ...removeIcs]
    let genrandField = ''
    if (imageScale != undefined && workType == undefined) {
      let result = this.generateSql_Lib(wx_user, removeSql, removeSql_Ic, removeIds, removeIcs, imageScale)
      querySql = result.sql
      paramsList = result.paramsList
      genrandField = ',video.genrand'
    } else {
      paramsList = [wx_user, wx_user, wx_user, workType, workType, ...removeIds, ...removeIcs]
    }
    let { sql, beforeParams, afterParams } = this.getQueryVideoField(wx_user, querySql, '', ` ,video.post_answer ${genrandField}`)
    let queryParams = [...beforeParams, ...paramsList, ...afterParams, skip, take]
    let order = 'order by video.create_time desc'
    let limit = 'limit ?,?'
    if (imageScale !== undefined && workType == undefined) {
      queryParams = [...beforeParams, ...paramsList, ...afterParams]
      order = 'order by video.genrand asc'
      limit = ''
    }
    return this.videoRepository.query(`
      select 
        ${sql}
      ${order}
      ${limit}
    `, queryParams)

  }

  generateSql_Ic(wx_user, where, whereVideo, removeSql, removeSql_Ic, removeIds, removeIcs, imageScale) {
    let list = []
    let paramsList = []
    let getRandom = () => {
      let number = Math.random() * 100
      if (number <= imageScale) {
        return 1
      } else {
        return 0
      }
    }
    let generateSql = (rand: number, count: number, i: number) => {
      let querySql = `
        select video.* from (
          select 'level${i}' as genrand,video.* from video
          where video.id in (
            select max(video.id) from video
            inner join internet_celebrity_group on internet_celebrity_group.id = video.ic_group
            where ${whereVideo} and video.check = 1 and video.is_home = 1 and video.delete_tag = 0 and video.ic_group is not null and (video.source = 0 or video.source = 2) and (
              video.ic_group in (
                select a.id from (
                  select distinct internet_celebrity_group.id from internet_celebrity_group 
                  left join platform on platform.ic_group = internet_celebrity_group.id
                  inner join video on video.ic_group = internet_celebrity_group.id
                  where ${where} and internet_celebrity_group.id not in (
                    select ic_group from watch_record_ic where wx_user = ?
                  ) ${removeSql_Ic}
                ) a
              )
              or ((video.overseas = 3 or video.overseas = 1) and video.original = 1)
            )
            and video.ic_group not in (
              select watch_record_ic.ic_group from watch_record_ic
              where watch_record_ic.wx_user = ?
            )
            and video.id not in (
              select watch_record.video_id from watch_record
              where watch_record.wx_user = ?
            )
            and video.id not in (
              select video_id from reward_success
              where reward_success.unit_price = 20000
            )
            ${removeSql}
            group by video.ic_group
          )
          and video.type = ?
          order by video.create_time desc
          limit 0,${count}
        ) video
      `
      paramsList.push(...[wx_user, ...removeIcs, wx_user, wx_user, ...removeIds, getRandom()])
      return querySql
    }
    for (let i = 0; i < 3; i++) {
      let rand = parseInt((Math.random() * 100).toString())
      let count = 1
      if (i === 1) {
        count = 2
      } else if (i === 2) {
        count = 4
      }
      list.push(generateSql(rand, count, i + 1))
    }

    let sql = `(
      select video.* from (
        ${list.join(' union ')}
      ) video
    ) video`
    return { sql, paramsList }
  }

  /**
   * 网红作品
   * @param skip 
   * @param take 
   * @param wx_user 
   * @param workType 
   * @param removeIds 
   * @returns 
   */
  findAll_IcWorks(skip: number, take: number, wx_user: string, workType: number, removeIds: [], removeIcs: [], commend: boolean, imageScale?: number) {
    let removeSql: any = []
    removeIds = removeIds || []
    removeIds.map(e => {
      removeSql.push(`video.id != ?`)
    })
    if (removeSql.length > 0) {
      removeSql = ` and (${removeSql.join(' and ')})`
    } else {
      removeSql = ''
    }
    let removeSql_Ic: any = []
    removeIcs = removeIcs || []
    removeIcs.map(e => {
      removeSql_Ic.push(`video.ic_group != ?`)
    })
    if (removeSql_Ic.length > 0) {
      removeSql_Ic = ` and (${removeSql_Ic.join(' and ')})`
    } else {
      removeSql_Ic = ''
    }

    // internet_celebrity_group.type = 2 认证后上传的作品
    // internet_celebrity_group.type = 3 未认证上传的作品
    let where = `(
      (
        video.overseas = 1 and video.profit_type = 0 and video.original = 1
      )
      or (
        video.overseas = 3 and video.profit_type = 0 and video.original = 1
      )
      or(
        (video.overseas = 0 or video.original = 0) 
        and (
          (internet_celebrity_group.type = 0 and (platform.platform in (select setting.value from setting where setting.key = 'level3')))
          or internet_celebrity_group.type = 3
        )
        and (
          (video.original = 0 and (video.in_ic = 0 or video.in_ic is null))
          or (video.original = 1 and video.in_ic = 0)
        )
      )
    )`
    let whereVideo = `(
      (
        video.overseas = 1 and video.profit_type = 0 and video.original = 1
      )
      or (
        video.overseas = 3 and video.profit_type = 0 and video.original = 1
      )
      or(
        (video.overseas = 0 or video.original = 0) 
        and (
          (internet_celebrity_group.type = 0 and internet_celebrity_group.id in (select platform.ic_group from platform inner join setting on setting.value = platform.platform where setting.key = 'level3'))
          or internet_celebrity_group.type = 3
        )
        and (
          (video.original = 0 and (video.in_ic = 0 or video.in_ic is null))
          or (video.original = 1 and video.in_ic = 0)
        )
      )
    )`
    if (commend) {
      where = `(
        platform.platform in (select setting.value from setting where setting.key = 'level3')
      )`
    }
    let querySql = `
      (
        select * from video
        where video.id in (
          select max(video.id) from video
          inner join internet_celebrity_group on internet_celebrity_group.id = video.ic_group
          where ${whereVideo} and video.check = 1 and video.is_home = 1 and video.delete_tag = 0 and video.ic_group is not null and (video.source = 0 or video.source = 2) and (
            video.ic_group in (
              select a.id from (
                select distinct internet_celebrity_group.id from internet_celebrity_group 
                left join platform on platform.ic_group = internet_celebrity_group.id
                inner join video on video.ic_group = internet_celebrity_group.id
                where ${where} and internet_celebrity_group.id not in (
                  select ic_group from watch_record_ic where wx_user = ?
                ) ${removeSql_Ic}
              ) a
            )
          )
          and video.ic_group not in (
            select watch_record_ic.ic_group from watch_record_ic
            where watch_record_ic.wx_user = ?
          )
          and video.id not in (
            select watch_record.video_id from watch_record
            where watch_record.wx_user = ?
          )
          and video.id not in (
            select video_id from reward_success
            where reward_success.unit_price = 20000
          )
          ${workType !== undefined ? ' and (video.type = ? or ? = -1)' : ''}
          ${removeSql}
          group by video.ic_group
        )
      ) video
    `
    let paramsList: any = [wx_user, ...removeIcs, wx_user, wx_user, ...removeIds]
    let order = 'order by video.create_time desc'
    let limit = 'limit ?,?'
    let generarandField = ''
    if (imageScale !== undefined && workType == undefined) {
      let result = this.generateSql_Ic(wx_user, where, whereVideo, removeSql, removeSql_Ic, removeIds, removeIcs, imageScale)
      querySql = result.sql
      paramsList = result.paramsList
      order = 'order by video.genrand asc'
      limit = ''
      generarandField = ',video.genrand'
    } else {
      paramsList = [wx_user, ...removeIcs, wx_user, wx_user, workType, workType, ...removeIds]
    }
    let { sql, beforeParams, afterParams } = this.getQueryVideoField(wx_user, querySql, undefined, generarandField)
    let sqlParams = [...beforeParams, ...paramsList, ...afterParams, skip, take]
    if (imageScale !== undefined && workType == undefined) {
      sqlParams = [...beforeParams, ...paramsList, ...afterParams]
    }
    return this.videoRepository.query(`
      select 
        ${sql}
      ${order}
      ${limit}
    `, sqlParams)
  }

  /**
   * 生成第一堆sql
   * @param wx_user 
   * @param removeSql 
   * @param removeIds 
   * @param imageScale 
   * @returns 
   */
  generateSql_Question(wx_user, removeSql, removeIds, imageScale) {
    let sql = ``
    let paramsList = []
    let getRandom = () => {
      let number = Math.random() * 100
      if (number <= imageScale) {
        return 1
      } else {
        return 0
      }
    }
    let generatesql = (rand: number, count: number, i: number) => {
      let gensql = `
        select video.* from (
          select 'level${i}' as genrand,video.* from video
          where video.check = 1 
            and video.is_home = 1 
            and video.id not in (
              select video_id from watch_record where wx_user = ?
            )
            and video.id not in (
              select video_id from reward_success
              where reward_success.unit_price = 20000
            ) 
            and video.ic_group is null
            ${removeSql}
            and video.type = ?
          order by video.create_time desc
          limit 0,${count}
        ) video`
      paramsList.push(...[wx_user, ...removeIds, getRandom()])
      return gensql
    }
    let list = []
    for (let i = 0; i < 3; i++) {
      let rand = parseInt((Math.random() * 100).toString())
      let count = 1
      if (i === 1) {
        count = 2
      } else if (i === 2) {
        count = 4
      }
      list.push(generatesql(rand, count, i + 1))
    }
    sql = `(
      select video.* from (
        ${list.join(' union ')}
      ) video
    ) video`
    return { sql, paramsList }
  }

  /**
   * 提问作品
   * @param skip 
   * @param take 
   * @param wx_user 
   * @param workType 
   * @param removeIds 
   * @returns 
   */
  findAll_QuestionWorks(skip: number, take: number, wx_user: string, workType: number, removeIds: [], last?: string, imageScale?: number) {
    let removeSql: any = []
    removeIds = removeIds || []
    removeIds.map(e => {
      removeSql.push(`video.id != ?`)
    })
    if (removeSql.length > 0) {
      removeSql = ` and (${removeSql.join(' and ')})`
    } else {
      removeSql = ''
    }

    let beforeParams = [wx_user, wx_user, wx_user, wx_user, wx_user, wx_user, wx_user]
    let afterParams = [wx_user, wx_user]
    //大额悬赏
    if (workType == 2) {
      if (last === 'last') {
        let result = this.getQueryVideoField(wx_user, `
          (
            select * from video
            where video.check = 1
            and video.is_home = 1 
            and video.id in (
              select video_id from reward_success
              where reward_success.unit_price = 20000
            ) 
            ${removeSql}
            order by video.create_time desc
          ) video
        `)
        beforeParams = result.beforeParams
        afterParams = result.afterParams
        return this.videoRepository.query(`
          select 
            ${result.sql}
          order by video.create_time desc
          limit ?,?
        `, [...beforeParams, ...removeIds, ...afterParams, skip, take])
      } else {
        let result = this.getQueryVideoField(wx_user, `
          (
            select * from video
            where video.check = 1 
            and video.is_home = 1
            and video.id not in (
              select video_id from watch_record where wx_user = ?
            )
            and video.id in (
              select video_id from reward_success
              where reward_success.unit_price = 20000
            ) 
            ${removeSql}
          ) video
        `)
        beforeParams = result.beforeParams
        afterParams = result.afterParams
        return this.videoRepository.query(`
          select 
            ${result.sql}
          order by video.create_time desc
          limit ?,?
        `, [...beforeParams, wx_user, ...removeIds, ...afterParams, skip, take])
      }
    } else {
      let sql = ``
      let imageScaleList = []
      let paramsList = []
      let generarand = ''
      if (imageScale !== undefined && workType == undefined) {
        let reusltGenSql = this.generateSql_Question(wx_user, removeSql, removeIds, imageScale)
        sql = reusltGenSql.sql
        paramsList = reusltGenSql.paramsList
        generarand = ', video.genrand'
      } else {
        sql = `
          (
            select * from video
            where video.check = 1 
            and video.is_home = 1 
            and video.id not in (
              select video_id from watch_record where wx_user = ?
            )
            and video.id not in (
              select video_id from reward_success
              where reward_success.unit_price = 20000
            ) 
            and video.ic_group is null
            ${workType != undefined ? ` and (video.type = ? or ? = -1)` : ''}
            ${removeSql}
          ) video
        `
        paramsList.push(workType)
        paramsList.push(workType)
      }
      let result = this.getQueryVideoField(wx_user, sql, undefined, generarand)
      beforeParams = result.beforeParams
      afterParams = result.afterParams

      let sqlParams = [...beforeParams, wx_user, ...paramsList, ...removeIds, ...afterParams, skip, take]
      let limit = 'limit ?,?'
      let order = 'order by video.create_time desc'
      if (imageScale !== undefined && workType == undefined) {
        sqlParams = [...beforeParams, ...paramsList, ...afterParams]
        limit = ''
        order = 'order by video.genrand asc'
      }
      return this.videoRepository.query(`
        select 
          ${result.sql}
        ${order}
        ${limit}
      `, sqlParams)
    }
  }

  /**
   * 清空第三堆
   * @param wx_user 
   * @param workType 
   */
  async clearIcVideoList(wx_user, workType) {
    await this.watchRecordIcRepository.query(`
      delete watch_record_ic from watch_record_ic
      inner join video on video.ic_group = watch_record_ic.ic_group
      inner join internet_celebrity_group on internet_celebrity_group.id = video.ic_group
      where video.check = 1 and video.is_home = 1 and (video.source = 0 or video.source = 2) and video.ic_group in (
        select a.id from (
          select distinct internet_celebrity_group.id from internet_celebrity_group 
          left join platform on platform.ic_group = internet_celebrity_group.id
          inner join video on video.ic_group = internet_celebrity_group.id
          where (
            (
              video.overseas = 1 and video.profit_type = 0 and video.original = 1
            )
            or (
              video.overseas = 3 and video.profit_type = 0 and video.original = 1
            )
            or(
              (video.overseas = 0 or video.original = 0) 
              and (
                (internet_celebrity_group.type = 0 and (platform.platform in (select setting.value from setting where setting.key = 'level3')))
                or internet_celebrity_group.type = 3
              )
              and (
                (video.original = 0 and (video.in_ic = 0 or video.in_ic is null))
                or (video.original = 1 and video.in_ic = 0)
              )
            )
          )
        ) a
      )
      and (
        (
          video.overseas = 1 and video.profit_type = 0 and video.original = 1
        )
        or (
          video.overseas = 3 and video.profit_type = 0 and video.original = 1
        )
        or(
          (video.overseas = 0 or video.original = 0) 
          and (
            (internet_celebrity_group.type = 0 and internet_celebrity_group.id in (select platform.ic_group from platform inner join setting on setting.value = platform.platform where setting.key = 'level3'))
            or internet_celebrity_group.type = 3
          )
          and (
            (video.original = 0 and (video.in_ic = 0 or video.in_ic is null))
            or (video.original = 1 and video.in_ic = 0)
          )
        )
      )
      and video.id not in (
        select video_id from reward_success
        where reward_success.unit_price = 20000
      ) 
      and watch_record_ic.wx_user = ? and watch_record_ic.work_type = ?
    `, [wx_user, workType])
  }

  /**
   * 清空第二堆
   * @param wx_user 
   * @param workType 
   */
  async clearLibVideoList(wx_user, workType) {
    await this.watchRecordIcRepository.query(`
      delete watch_record_ic from watch_record_ic
      inner join (
        select * from watch_record_ic
        where watch_record_ic.ic_group not in (
          select video.ic_group from video
          where video.check = 1 and video.source = 2 and video.ic_group in (
            select a.id from (
              select distinct internet_celebrity_group.id from internet_celebrity_group 
              left join platform on platform.ic_group = internet_celebrity_group.id
              inner join video on video.ic_group = internet_celebrity_group.id
              where (
                (
                  internet_celebrity_group.type = 2 
                )
                or(
                  internet_celebrity_group.type = 0 and platform.platform in (select setting.value from setting where setting.key = 'level3')
                )
                or (
                  internet_celebrity_group.type = 3 
                )
                or ((video.overseas = 3 or video.overseas = 1) and video.original = 1)
              )
            ) a
          )
          and video.id not in (
            select video_id from reward_success
            where reward_success.unit_price = 20000
          )
        )
      ) video on video.ic_group = watch_record_ic.ic_group
      where watch_record_ic.wx_user = ? and watch_record_ic.work_type = ?
    `, [wx_user, workType])
  }

  /**
   * 查询有答案的视频
   * @param skip
   * @param take
   * @param wx_user
   * @param loadType
   * @param minId
   * @returns
   */
  async findAll_Forent_Yes_Answer_New(pageSize: number, pageIndex: number, wx_user?: string, loadType?: string
    , isRemoveIc?: boolean, loadedIds?: [], loadedIcs?: [], commend?: boolean, last?: string):
    Promise<{ video: any[], answer: any[], multiImg: any[], pageIndex: number }> {
    pageIndex = 0
    let result = await this.GetVideoCount(pageSize, loadType)
    let arr = result.arr
    let lcm = result.lcm
    let videoList = []
    let loadedIdsSource: any = loadedIds ? [...loadedIds] : []
    let loadedIcsSource: any = loadedIcs ? [...loadedIcs] : []
    let ids: any = loadedIds || []
    let ics: any = loadedIcs || []
    let pageSizeSource = pageSize
    //当前查看的视频数
    let findList = arr.slice(pageSize * pageIndex, pageSize * (pageIndex + 1))

    //视频库视频
    let myLibVideos = findList.filter(e => e.type === 'lib')
    //视频库图片
    let myLibImages = findList.filter(e => e.type === 'lib')
    //网红视频
    let icVideos = findList.filter(e => e.type === 'ic')
    //网红图片
    let icImages = findList.filter(e => e.type === 'ic')
    //提问视频
    let questionVideos = findList.filter(e => e.type === 'question')
    //提问图片
    let questionImages = findList.filter(e => e.type === 'question')


    let blImageScale: Setting = await this.settingRepository.findOne({ where: { key: 'image_scale' } })
    let imageScale = 50
    if (blImageScale && blImageScale.value) {
      imageScale = Number(blImageScale.value)
    }

    let getRandom = () => {
      let number = Math.random() * 100
      if (number <= imageScale) {
        return 1
      } else {
        return 0
      }
    }

    let maxImageCount = 3
    let maxImage = 0
    let typeList = []
    let setType = (type) => {
      if (typeList[typeList.length - 1] == 1) {
        maxImage++
      } else {
        maxImage = 0
      }
      typeList.push(type)
    }
    let loop = async (type?: any) => {
      pageSize = 3

      let otherType = type === undefined ? -1 : type

      let currentType_question = type === undefined ? getRandom() : type

      if (otherType === -1) {
        setType(currentType_question)
        if (maxImage >= maxImageCount) {
          currentType_question = 0
          maxImage = 0
          typeList = []
        }
      }
      if (currentType_question === undefined) {
        currentType_question = 0
      }
      //提问视频
      let questionVideoWorks: any = await this.findAll_QuestionWorks(0, pageSize, wx_user, type, ids, last, imageScale)
      let newList: any = []
      for (let i = 0; i < pageSize; i++) {
        let findItem = questionVideoWorks.find(e => {
          if (e.genrand == `level${i + 1}` && !newList.find(c => c.id == e.id)) {
            return true
          }
        })
        if (findItem) {
          newList.push(findItem)
        }
      }
      questionVideoWorks = newList
      let surplusLen = 3 - questionVideoWorks.length
      if (surplusLen > 0) {
        console.log('剩余提问', questionVideoWorks.map(e => e.type))
        let removeQuestionIds: any = []
        removeQuestionIds.push(...ids)
        removeQuestionIds.push(...questionVideoWorks.map(e => e.id))
        let surplusResult = await this.findAll_QuestionWorks(0, surplusLen, wx_user, otherType, removeQuestionIds, last)
        questionVideoWorks.push(...surplusResult)
      }
      console.log(questionVideoWorks.length, 'questionVideoWorks22', questionVideoWorks.map(e => e.type), imageScale)




      let currentType_lib = type === undefined ? getRandom() : type
      if (otherType === -1) {
        setType(currentType_lib)
        if (maxImage >= maxImageCount) {
          currentType_lib = 0
          maxImage = 0
          typeList = []
        }
      }
      if (currentType_lib === undefined) {
        currentType_lib = 0
      }
      //视频库视频
      let libVideoWorks = []
      if (currentType_lib !== 2) {

        let getLibList = async () => {
          let libVideoWorks = await this.findAll_LibWorks(0, pageSize, wx_user, type, ids, ics, imageScale)
          let newList_Lib: any = []
          for (let i = 0; i < pageSize; i++) {
            let findItem = libVideoWorks.find(e => {
              if (e.genrand == `level${i + 1}` && !newList_Lib.find(c => c.id == e.id)) {
                return true
              }
            })
            if (findItem) {
              newList_Lib.push(findItem)
            }
          }
          libVideoWorks = newList_Lib

          let surplusLibLen = 3 - libVideoWorks.length
          if (surplusLibLen > 0) {
            console.log('剩余视频库')
            let surplusLibIds: any = []
            surplusLibIds.push(...ids)
            surplusLibIds.push(...libVideoWorks.map(e => e.id))
            let surplusLibIcs: any = []
            surplusLibIcs.push(...ics)
            surplusLibIcs.push(...libVideoWorks.map(e => e.ic_group))
            let surplusList = await this.findAll_LibWorks(0, surplusLibLen, wx_user, otherType, surplusLibIds, surplusLibIcs)
            libVideoWorks.push(...surplusList)
          }
          console.log(libVideoWorks.length, 'libVideoWorks', libVideoWorks.map(e => e.type), imageScale)

          libVideoWorks.filter(e => e.post_answer == 1).map(e => {
            e.is_question_answer = true
            delete e.post_answer
          })

          ics.push(...libVideoWorks.filter(e => e.ic_group).map(e => e.ic_group))
          ics = [...new Set([...ics])]

          ids.push(...libVideoWorks.map(e => e.id))
          ids = [...new Set([...ids])]

          return libVideoWorks
        }

        libVideoWorks = await getLibList()
        let workType = utils.getMainWorkType(loadType)
        let count = 4
        let loopGetLib = async () => {
          let otn = 3 - libVideoWorks.length
          if (otn > 0) {
            await this.clearLibVideoList(wx_user, workType)
            libVideoWorks.push(...(await getLibList()).slice(0, otn))
            count--
            if (count > 0) {
              await loopGetLib()
            }
          }
        }
        await loopGetLib()
      }

      let currentType_ic = type === undefined ? getRandom() : type
      if (otherType === -1) {
        setType(currentType_ic)
        if (maxImage >= maxImageCount) {
          currentType_ic = 0
          maxImage = 0
          typeList = []
        }
      }
      if (currentType_ic === undefined) {
        currentType_ic = 0
      }
      //网红视频、tiktok ins视频
      let icVideoWorks = []
      if (currentType_ic != 2) {
        let getIcList = async () => {
          let icVideoWorks = await this.findAll_IcWorks(0, pageSize, wx_user, type, ids, ics, commend, imageScale)
          console.log(icVideoWorks.length, 'icVideoWorks', icVideoWorks.map(e => e.type), imageScale, icVideoWorks.map(e => e.genrand))
          let newList_Ic: any = []
          for (let i = 0; i < pageSize; i++) {
            let findItem = icVideoWorks.find(e => {
              if (e.genrand == `level${i + 1}` && !newList_Ic.find(c => c.id == e.id)) {
                return true
              }
            })
            if (findItem) {
              newList_Ic.push(findItem)
            }
          }
          icVideoWorks = newList_Ic

          let surplusIcLen = 3 - icVideoWorks.length
          if (surplusIcLen > 0) {
            console.log('剩余网红')
            let surplusIcIds: any = []
            surplusIcIds.push(...ids)
            surplusIcIds.push(...icVideoWorks.map(e => e.id))
            let surplusIcIcs: any = []
            surplusIcIcs.push(...ics)
            surplusIcIcs.push(...icVideoWorks.map(e => e.ic_group))

            let surplusList = await this.findAll_IcWorks(0, surplusIcLen, wx_user, otherType, surplusIcIds, surplusIcIcs, commend)
            icVideoWorks.push(...surplusList)
          }

          ics.push(...icVideoWorks.filter(e => e.ic_group).map(e => e.ic_group))
          ics = [...new Set([...ics])]

          ids.push(...icVideoWorks.map(e => e.id))
          ids = [...new Set([...ids])]
          return icVideoWorks
        }
        icVideoWorks = await getIcList()
        let workType = utils.getMainWorkType(loadType)
        let count = 4
        let loopGetIc = async () => {
          let otn = 3 - icVideoWorks.length
          if (otn > 0) {
            await this.clearIcVideoList(wx_user, workType)
            icVideoWorks.push(...(await getIcList()).slice(0, otn))
            count--
            if (count > 0) {
              await loopGetIc()
            }
          }
        }
        await loopGetIc()

        icVideoWorks.filter(e => e.post_answer == 1).map(e => {
          e.is_question_answer = true
        })
      }

      commend = false

      findList.slice(0, 9).map(e => {
        switch (e.type) {
          case 'lib'://视频库
            let findVideo_lib: any = libVideoWorks.find((c: any) => !c.isremove)
            if (findVideo_lib) {
              findVideo_lib.isremove = true
              findVideo_lib.workSource = 'lib'
              findVideo_lib.sourceT = findVideo_lib.type === VideoEnum.video ? 'video' : 'image'
              videoList.push(findVideo_lib)
            }
            break;
          case 'ic'://网红
            let findVideo_ic: any = icVideoWorks.find((c: any) => !c.isremove)
            if (findVideo_ic) {
              findVideo_ic.isremove = true
              findVideo_ic.workSource = 'ic'
              findVideo_ic.sourceT = findVideo_ic.type === VideoEnum.video ? 'video' : 'image'
              videoList.push(findVideo_ic)
            }
            break;
          case 'question'://提问
            let findVideo_question: any = questionVideoWorks.find((c: any) => !c.isremove)
            if (findVideo_question) {
              findVideo_question.isremove = true

              findVideo_question.workSource = 'question'
              //大额悬赏
              if (type === 2) {
                if (findVideo_question.otherNetwork_ic_info || findVideo_question.authen_work || findVideo_question.otherNetwork) {
                  findVideo_question.workSource = 'ic'
                } else if (findVideo_question.ic_group) {
                  findVideo_question.workSource = 'lib'
                }
                if (findVideo_question.post_answer == 1) {
                  findVideo_question.is_question_answer = true
                } else {
                  findVideo_question.is_question_answer = false
                  // findVideo_question.workSource = 'question'
                }
              }

              findVideo_question.sourceT = findVideo_question.type === VideoEnum.video ? 'video' : 'image'
              videoList.push(findVideo_question)
            }
            break;
        }
      })
    }
    if (loadType === 'all') {
      await loop()
      // await loop()
      // await loop()
    } else {
      let typeC = loadType === 'image' ? 1 : 2
      if (loadType === 'video' && last === 'last') {
        await loop(typeC)
      } else {
        await loop(typeC)
      }
    }

    let video_ids_sql_list = []
    let video_ids_sql_field = []
    videoList.map(e => {
      video_ids_sql_list.push(` b.video_id = ? `)
      video_ids_sql_field.push(e.id)
    })

    let video_ids_sql_text = ''
    if (video_ids_sql_list.length > 0) {
      video_ids_sql_text = ' and (' + video_ids_sql_list.join(' or ') + ')'
    }

    //读取答案
    let answerList = await this.videoRepository.query(`
      select b.id,b.video_id,b.wx_user,b.create_time,b.check,b.check_time,b.type,b.answer_template_id,b.id as answer_id
        ,c.use_wx_user,e.platform,e.ic_name,e.img,e.img_id, c.status as profit_status,b.reject_auto_time
      from answer b
      left join profit as c on c.answer_id = b.id
      left join answer_info as e on e.answer_id = b.id
      where b.delete_tag = 0 ${video_ids_sql_text}
    `, video_ids_sql_field)

    //读取多图
    let multiImg = await this.videoRepository.query(`
      select b.*,c.*,d.img as multi_img
      from answer b
      left join profit as c on c.answer_id = b.id
      left join multi_img as d on d.video_id = b.video_id
      where b.delete_tag = 0 ${video_ids_sql_text}
      order by d.cover desc,d.id asc
    `, video_ids_sql_field)

    //查询是否共同提问过
    let questions = await this.videoRepository.query(`
      select * from questions b
      where b.wx_user = ? ${video_ids_sql_text}
    `, [wx_user, ...video_ids_sql_field])

    questions.map(e => {
      let findWork = videoList.find(c => c.id === e.video_id)
      if (findWork) {
        findWork.isQuestion = true
      }
    })

    //查询悬赏金额
    let videoRewardList = []
    videoList.filter(e => e.isreward).map(e => {
      let item = {
        video_id: e.id,
      }
      videoRewardList.push(item)
    })
    if (videoRewardList.length > 0) {
      let rewardList = await this.rewardSuccessRepository.find({ where: videoRewardList })
      this.setRewardPrice(videoList, rewardList)
    }



    //没有网红了，清空网红
    if (loadType !== 'video') {
      // if((videoList.filter(e => e.workSource === 'lib').length != 3 || videoList.filter(e => e.workSource === 'ic').length != 3) && !isRemoveIc){
      //   let workType = utils.getMainWorkType(loadType)
      //   if(videoList.filter(e => e.workSource === 'lib').length != 3){
      //     //清空第二堆
      //     await this.watchRecordIcRepository.query(`
      //       delete watch_record_ic from watch_record_ic
      //       inner join (
      //         select * from watch_record_ic
      //         where watch_record_ic.ic_group not in (
      //           select video.ic_group from video
      //           where video.check = 1 and video.source = 2 and video.ic_group in (
      //             select a.id from (
      //               select distinct internet_celebrity_group.id from internet_celebrity_group 
      //               left join platform on platform.ic_group = internet_celebrity_group.id
      //               inner join video on video.ic_group = internet_celebrity_group.id
      //               where (
      //                 (
      //                   internet_celebrity_group.type = 2 
      //                 )
      //                 or(
      //                   internet_celebrity_group.type = 0 and platform.platform in (select setting.value from setting where setting.key = 'level3')
      //                 )
      //                 or (
      //                   internet_celebrity_group.type = 3 
      //                 )
      //                 or ((video.overseas = 3 or video.overseas = 1) and video.original = 1)
      //               )
      //             ) a
      //           )
      //           and video.id not in (
      //             select video_id from reward_success
      //             where reward_success.unit_price = 20000
      //           )
      //         )
      //       ) video on video.ic_group = watch_record_ic.ic_group
      //       where watch_record_ic.wx_user = ? and watch_record_ic.work_type = ?
      //     `,[wx_user, workType])
      //   }
      //   if(videoList.filter(e => e.workSource === 'ic').length != 3){
      //     //清空第三堆
      //     await this.watchRecordIcRepository.query(`
      //       delete watch_record_ic from watch_record_ic
      //       inner join video on video.ic_group = watch_record_ic.ic_group
      //       inner join internet_celebrity_group on internet_celebrity_group.id = video.ic_group
      //       where video.check = 1 and video.is_home = 1 and (video.source = 0 or video.source = 2) and video.ic_group in (
      //         select a.id from (
      //           select distinct internet_celebrity_group.id from internet_celebrity_group 
      //           left join platform on platform.ic_group = internet_celebrity_group.id
      //           inner join video on video.ic_group = internet_celebrity_group.id
      //           where (
      //             (
      //               video.overseas = 1 and video.profit_type = 0 and video.original = 1
      //             )
      //             or (
      //               video.overseas = 3 and video.profit_type = 0 and video.original = 1
      //             )
      //             or(
      //               (video.overseas = 0 or video.original = 0) 
      //               and (
      //                 (internet_celebrity_group.type = 0 and (platform.platform in (select setting.value from setting where setting.key = 'level3')))
      //                 or internet_celebrity_group.type = 3
      //               )
      //               and (
      //                 (video.original = 0 and (video.in_ic = 0 or video.in_ic is null))
      //                 or (video.original = 1 and video.in_ic = 0)
      //               )
      //             )
      //           )
      //         ) a
      //       )
      //       and (
      //         (
      //           video.overseas = 1 and video.profit_type = 0 and video.original = 1
      //         )
      //         or (
      //           video.overseas = 3 and video.profit_type = 0 and video.original = 1
      //         )
      //         or(
      //           (video.overseas = 0 or video.original = 0) 
      //           and (
      //             (internet_celebrity_group.type = 0 and internet_celebrity_group.id in (select platform.ic_group from platform inner join setting on setting.value = platform.platform where setting.key = 'level3'))
      //             or internet_celebrity_group.type = 3
      //           )
      //           and (
      //             (video.original = 0 and (video.in_ic = 0 or video.in_ic is null))
      //             or (video.original = 1 and video.in_ic = 0)
      //           )
      //         )
      //       )
      //       and video.id not in (
      //         select video_id from reward_success
      //         where reward_success.unit_price = 20000
      //       ) 
      //       and watch_record_ic.wx_user = ? and watch_record_ic.work_type = ?
      //     `,[wx_user, workType])
      //   }

      //   return await this.findAll_Forent_Yes_Answer_New(pageSizeSource, pageIndex, wx_user, loadType, true, loadedIdsSource, loadedIcsSource, commend)
      // }

      // if((videoList.filter(e => e.workSource === 'lib').length === 0 || videoList.filter(e => e.workSource === 'ic').length === 0) && !isRemoveIc){
      //   let workType = utils.getMainWorkType(loadType)
      //   //清空第三堆
      //   if(videoList.filter(e => e.workSource === 'ic').length === 0){

      //   }
      //   if(videoList.filter(e => e.workSource === 'lib').length === 0){

      //   }
      //   return await this.findAll_Forent_Yes_Answer_New(pageSizeSource, pageIndex, wx_user, loadType, true, loadedIdsSource, loadedIcsSource, commend)
      // }
      // else if(videoList.filter(e => e.workSource === 'lib' || e.workSource === 'ic').length === 0 && !isRemoveIc){
      //   let workType = utils.getMainWorkType(loadType)
      //   await this.watchRecordIcRepository.delete({wx_user: wx_user, work_type: workType})
      //   return await this.findAll_Forent_Yes_Answer_New(pageSize, pageIndex, wx_user, loadType, true, ids)
      // }
      if (videoList.length === 1 && !isRemoveIc) {
        //如果是一个视频，再获取一轮
        pageIndex++
        let ids: any = videoList.map(e => e.id)
        let nextList = await this.findAll_Forent_Yes_Answer_New(pageSize, pageIndex, wx_user, loadType, true, ids, ics)
        videoList.push(...nextList.video)
        answerList.push(...nextList.answer)
        multiImg.push(...nextList.multiImg)
      }
    } else if (videoList.length == 0 && !isRemoveIc) {
      let nextList = await this.findAll_Forent_Yes_Answer_New(pageSize, pageIndex, wx_user, loadType, true, [], undefined, undefined, 'last')
      videoList.push(...nextList.video)
      answerList.push(...nextList.answer)
      multiImg.push(...nextList.multiImg)
    }
    if (videoList.length > 0) {
      pageIndex++
    }

    return { video: videoList, answer: answerList, multiImg: multiImg, pageIndex: (pageSize * pageIndex) < lcm ? pageIndex : 0 }
  }

  findOne(id: number, notCertified?: boolean): Promise<any> {
    if (notCertified) {
      return this.videoAbroadRepository.findOne({ where: { id } });
    } else {
      return this.videoRepository.findOne({ where: { id } });
    }
  }

  async remove(id: number): Promise<void> {
    await this.videoRepository.delete(id);
  }

  async remove_video_library_manager(id: number): Promise<any> {
    //查询视频
    //查询视频详情
    let findVideo = await this.videoRepository.findOne({ where: { id: id } })
    if (!findVideo) {
      return '视频不存在'
    }

    //查询视频是否可以删除
    // 1、普通悬赏、大额悬赏
    let findRewardSuccess = await this.rewardSuccessRepository.findOne({ where: { video_id: id, wx_user: Not(findVideo.wx_user) } })
    if (findRewardSuccess) {
      return findRewardSuccess.unit_price === 20000 ? '已有大额悬赏，无法删除' : '已有悬赏，无法删除'
    }
    // 2、第二堆，同提问5毛/产生过收益
    let findProfit = await this.profitRepository.query(`
      select profit.* from profit
      inner join answer on answer.id = profit.answer_id
      where answer.check = 1 and answer.video_id = ? and profit.unit_price > 0
    `, [id])
    if (findProfit.length > 0) {
      return '已产生收益，无法删除'
    }

    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      //删除一个视频
      await this.videoRepository.createQueryBuilder(null, queryRunner).delete().where({ id: id }).execute()
      await this.answerRepository.createQueryBuilder(null, queryRunner).delete().where({ video_id: id }).execute()
      //查询自己的悬赏
      let findReward: RewardSuccess = await this.rewardSuccessRepository.findOne({ where: { video_id: id } })
      if (findReward) {
        //删除自己的悬赏
        await this.rewardRepository.createQueryBuilder(null, queryRunner).delete().where({ video_id: id }).execute()
        await this.rewardSuccessRepository.createQueryBuilder(null, queryRunner).delete().where({ video_id: id }).execute()

        //删除转悬赏的一笔消费
        let findRecharge: RechargeFlow[] = await this.rechargeFlowRepository.query(`
          select * from recharge_flow
          where create_time = ? and amount = 20000
        `, [findReward.pay_time])
        if (findRecharge.length > 0) {
          await this.rechargeFlowRepository.createQueryBuilder(null, queryRunner).delete().where({ id: findRecharge[0].id }).execute()
        }
      }
      await queryRunner.commitTransaction()
      await queryRunner.release();
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }

  async remove_video_library(id: number, notCertified?: boolean): Promise<any> {
    //查询视频
    //查询视频详情
    let findVideo = notCertified ? await this.videoAbroadRepository.findOne({ where: { id: id } }) : await this.videoRepository.findOne({ where: { id: id } })
    if (!findVideo) {
      return '视频不存在'
    }
    //查询视频是否是今天之前的视频
    let startTime = utils.Format(new Date(findVideo.create_time), 'yyyy-MM-dd')
    let nowTime = utils.Format(new Date(), 'yyyy-MM-dd')
    if (startTime !== nowTime) {
      //验证今天之前的视频当天是否删除了20次了
      startTime = new Date()
      let endTime = new Date()
      endTime.setHours(23)
      endTime.setMinutes(59)
      endTime.setSeconds(59)

      const limit = await this.rateLimiter.consume_manager('remove_video_library', 1, (endTime.getTime() - startTime.getTime()) / 1000)
      if (!limit) {
        return '删除超过限制，请明日再试！'
      }
    }

    //查询视频是否可以删除
    // 1、普通悬赏、大额悬赏
    let findRewardSuccess = await this.rewardSuccessRepository.findOne({ where: { video_id: id, wx_user: Not(findVideo.wx_user) } })
    if (findRewardSuccess) {
      return findRewardSuccess.unit_price === 20000 ? '已有大额悬赏，无法删除' : '已有悬赏，无法删除'
    }
    // 2、第二堆，同提问5毛/产生过收益
    let findProfit = await this.profitRepository.query(`
      select profit.* from profit
      inner join answer on answer.id = profit.answer_id
      where answer.check = 1 and answer.video_id = ? and profit.unit_price > 0
    `, [id])
    if (findProfit.length > 0) {
      return '已产生收益，无法删除'
    }

    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      //删除一个视频
      if (notCertified) {
        await this.videoAbroadRepository.createQueryBuilder(null, queryRunner).delete().where({ id: id }).execute()
        await this.answerAbroadRepository.createQueryBuilder(null, queryRunner).delete().where({ video_id: id }).execute()
      } else {
        await this.videoRepository.createQueryBuilder(null, queryRunner).delete().where({ id: id }).execute()
        await this.answerRepository.createQueryBuilder(null, queryRunner).delete().where({ video_id: id }).execute()
      }
      //查询自己的悬赏
      let findReward: RewardSuccess = await this.rewardSuccessRepository.findOne({ where: { video_id: id } })
      if (findReward) {
        //删除自己的悬赏
        await this.rewardRepository.createQueryBuilder(null, queryRunner).delete().where({ video_id: id }).execute()
        await this.rewardSuccessRepository.createQueryBuilder(null, queryRunner).delete().where({ video_id: id }).execute()

        //删除转悬赏的一笔消费
        let findRecharge: RechargeFlow[] = await this.rechargeFlowRepository.query(`
          select * from recharge_flow
          where create_time = ? and amount = 20000
        `, [findReward.pay_time])
        if (findRecharge.length > 0) {
          await this.rechargeFlowRepository.createQueryBuilder(null, queryRunner).delete().where({ id: findRecharge[0].id }).execute()
        }
      }
      await queryRunner.commitTransaction()
      await queryRunner.release();

      //清空缓存-视频
      await this.redisCacheService.clear(`videos:${id}*`)
      //清空缓存-关注
      if (findVideo?.ic_group) {
        await this.redisCacheService.clear(`*:icinfo:icgroup:${findVideo.ic_group}:videos`)
      }
      this.wsStartGateway.postUpdateVideo(id)
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }

  async create(video: Video): Promise<Video> {
    return await this.videoRepository.save(video);
  }

  getIDCard(works) {
    let id = ''
    let loop = async () => {
      //作品 A12345
      if (works) {
        id = utils.randomStringID(1, 5, true)
      } else {
        //问题 12345A
        id = utils.randomStringID(1, 5)
      }
      if (await this.videoRepository.findOne({ where: { id_card: id } })) {
        loop()
      }
    }
    loop()
    return id
  }

  /**
   * 微信端发布视频
   * @param wx_user
   * @param video
   * @param answer
   * @returns
   */
  async client_upload_video(wx_user: string, video: Video, multi_img?: MultiImg[], answerList?: AnswerInfo[], traceRelaTableList?: TraceRelaTable[], isOverseas?: Boolean) {
    //认证用户的作品，查询ic_group
    if (video.original == 1 && video.overseas === OverseasEnum.yes) {
      let ic_group = await this.internetCelebrityGroupRepository.findOne({ where: { wx_user: wx_user, type: EnumInternetCelebrityGroupTypeEnum.overseas } })
      if (ic_group) {
        video.ic_group = ic_group.id
      } else {
        return { error: '没有网红ID' }
      }
    }
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      video.id_card = this.getIDCard(video.original === OriginalEnum.yes)
      //创建一个视频
      let saveVideo: Video = await queryRunner.manager.save(video);
      if (!saveVideo) {
        throw new Error('创建视频失败')
      }
      let answerCheck = CheckEnum.no
      //认证了的是网红自己，答案直接审核通过
      if (isOverseas || video.original == OriginalEnum.yes) {
        answerCheck = CheckEnum.yes
      }

      let video_id = saveVideo.id
      //添加访问记录
      let watchRecord = new WatchRecord()
      watchRecord.create_time = new Date()
      watchRecord.video_id = video_id
      watchRecord.wx_user = wx_user
      await this.watchRecordRepository.createQueryBuilder(null, queryRunner).insert().into(WatchRecord).values(watchRecord).execute()

      //添加一个回答(提问无回答)
      if (video.original == OriginalEnum.yes) {
        let addAnswer = new Answer()
        addAnswer.wx_user = wx_user
        addAnswer.create_time = new Date()
        addAnswer.check = answerCheck
        addAnswer.type = isOverseas ? TypeEnum.author : TypeEnum.virtual
        addAnswer.video_id = video_id
        await queryRunner.manager.save(addAnswer)
        let answerListLen = answerList.length
        const addAnswerFn = () => {
          return new Promise((resolve, reject) => {
            //添加回答详情
            answerList.map(async (e: AnswerInfo) => {
              e.answer_id = addAnswer.id
              e.create_time = new Date()
              e.video_id = video_id
              await this.answerInfoRepository.createQueryBuilder(null, queryRunner)
                .insert()
                .into(AnswerInfo)
                .values(e)
                .execute()

              // await queryRunner.manager.save(e)
              if (--answerListLen === 0) {
                resolve(true)
              }
            })
          })
        }
        if (answerListLen > 0) {
          await addAnswerFn()
        }
      }
      let traceRelaTableListLen = traceRelaTableList.length
      const addTraceRelaTable = () => {
        return new Promise((resolve, reject) => {
          //添加图片审核关联
          traceRelaTableList.map(async (e: TraceRelaTable) => {
            e.create_time = new Date()
            await queryRunner.manager.save(e)
            if (--traceRelaTableListLen === 0) {
              resolve(true)
            }
          })
        })
      }
      if (traceRelaTableListLen > 0) {
        await addTraceRelaTable()
      }
      //如果是长图,添加图片
      let addImgError = ''
      if (multi_img?.length > 0) {
        let multi_imgLen = multi_img.length
        const addMultiImg = () => {
          return new Promise((resolve, reject) => {
            multi_img.map(async (e: MultiImg) => {
              let addMutImg = new MultiImg()
              addMutImg.cover = e.cover
              addMutImg.create_time = new Date()
              addMutImg.img = e.img
              addMutImg.img_id = e.img_id
              addMutImg.video_id = video_id
              addMutImg.trace_id = e.trace_id
              try {
                await queryRunner.manager.save(addMutImg)
              } catch (err) {
                addImgError = err
              } finally {
                if (--multi_imgLen === 0) {
                  resolve(true)
                }
              }
            })
          })
        }
        if (multi_imgLen > 0) {
          await addMultiImg()
        }
      }
      if (addImgError) {
        throw new Error(addImgError)
      }
      //如果是海外素材作者则删除平台信息
      if (isOverseas) {
        // //删除网红组
        // await this.internetCelebrityGroupRepository.createQueryBuilder(null,queryRunner).delete().where({wx_user: wx_user, type: EnumInternetCelebrityGroupTypeEnum.overseas}).execute()
        // //删除网红
        // await this.icRepository.createQueryBuilder(null,queryRunner).delete().where({wx_user: wx_user, overseas: 1}).execute()
        // //删除平台
        // await this.platformRepository.createQueryBuilder(null,queryRunner).delete().where({wx_user: wx_user, type: 2}).execute()
      }


      await queryRunner.commitTransaction()
      await queryRunner.release();
      return { result: video_id }
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return { error: err }
    }
  }


  async update_video_ic(video: Video): Promise<any> {
    let wx_user = video.wx_user
    let video_id = video.id
    //查询视频的回答
    let findAnswer: Answer[] = await this.answerRepository.query(`
      select a.* from answer a
      where a.video_id = ? and a.wx_user = ? and a.check = 1
      order by a.id asc
    `, [video_id, wx_user])
    //查询视频原始数据
    let findVideo = await this.videoRepository.findOne({ where: { id: video_id } })
    let concernList = []
    if (video.ic_group) {
      concernList = await this.videoRepository.query(`
        select concern.wx_user from concern
        where concern.concern_ic_group = ?  
      `, [video.ic_group])
    }
    //查询是不是第二堆
    let isLevel2 = false
    if (video.ic_group) {
      let level2Count = await this.internetCelebrityGroupRepository.query(`
        select count(1) as total from internet_celebrity_group 
        inner join platform on platform.ic_group = internet_celebrity_group.id
        where internet_celebrity_group.id = ?
          and internet_celebrity_group.type = 0
          and platform.platform not in (select setting.value from setting where setting.key = 'level3')
      `, [video.ic_group])
      if (Number(level2Count?.[0]?.total || 0) > 0) {
        isLevel2 = true
      }
    }
    if (isLevel2 || !video.ic_group) {
      let rand = Math.random() * 100
      if (rand <= 90) {
        // 使用示例
        const arr = [1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000];
        const sampleSize = 1;
        const sampled = this.sample(arr, sampleSize);
        if (sampled.length > 0) {
          rand = sampled[0]
        } else {
          rand = undefined
        }
      } else {
        rand = 10000
      }
      if (rand !== undefined) {
        video.basic_questions = rand
        if (video.ic_group) {
          let sj = parseInt(this.getRandomNumber(14, 33))
          let reward_count = rand * (sj / 100)
          let basic_reward = parseInt((reward_count * 30).toString())
          basic_reward = basic_reward + this.getRandomNumber(1, 9) * 30
          video.basic_reward = basic_reward
        } else {
          video.basic_reward = 0
        }
      }
      if (!video.ic_group) {
        video.basic_reward = this.getRandomNumber(100, 1000)
      }
    } else {
      if (video.ic_group) {
        video.basic_questions = 0
      }
      video.basic_reward = 0
    }
    //查询当前视频所有退款
    let findRefundIngList = []
    if (video.ic_group) {
      findRefundIngList = await this.profitRepository.query(`
        select distinct profit.id, answer.video_id,answer.id as answer_id,profit.author_wx_user, 
          profit.use_wx_user,profit.notes,profit.service_charge, profit.unit_price,profit.type,profit.update_time, profit.create_time, 'profit' as refund_type
        from profit
        inner join answer on answer.id = profit.answer_id
        where answer.video_id = ? and profit.status = 3
        union all
        select distinct profit_unlock_home.id, profit_unlock_home.video_id, answer.id as answer_id, video.wx_user as author_wx_user,
          profit_unlock_home.use_wx_user, null as notes, profit_unlock_home.service_charge, profit_unlock_home.unit_price, profit_unlock_home.type, profit_unlock_home.update_time, 
          profit_unlock_home.create_time, 'profit_unlock_home' as refund_type
        from profit_unlock_home
        inner join answer on answer.video_id = profit_unlock_home.video_id and answer.check = 1 and answer.delete_tag = 0
        inner join video on video.id = profit_unlock_home.video_id
        where profit_unlock_home.video_id = ? and profit_unlock_home.status = 3
      `, [video.id, video.id])
    }
    //查找此视频所有报错
    let findReportList: AnswerReportErrors[] = []
    if (findAnswer.length > 0 && video.ic_group) {
      findReportList = await this.answerReportErrorsRepository.query(`
        select answer_report_errors.*, answer.id as answer_id from answer_report_errors
        inner join answer on answer.id = answer_report_errors.answer_id
        where answer.video_id = ? and answer_report_errors.delete_tag = 0 and answer_report_errors.reset_error = 0
      `, [video_id])
    }

    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      if (findVideo.original != video.original) {
        video.id_card = this.getIDCard(video.original == OriginalEnum.yes)
      }
      await queryRunner.manager.update(Video, { id: video_id }, video);
      let noticeList: Notices[] = []
      let postMyData: any = []

      if (findAnswer.length > 0) {
        let addAnswer: Answer = findAnswer[0]
        let answer_id = addAnswer.id
        let questionList = await this.questionsIcRepository.find({ where: { video_id: video_id } })
        questionList.map(e => {
          postMyData.push({ video_id: e.video_id, wx_user: e.wx_user })
        })
        if (!video.ic_group) {
          //删除答案
          await this.answerRepository.createQueryBuilder(null, queryRunner).delete().where({ id: answer_id }).execute()
          //删除视频所有同提问的答案
          await this.questionsIcRepository.createQueryBuilder(null, queryRunner).update({ post_answer: null, answer_time: null }).where({ video_id: video_id }).execute()
          let profitList = await this.profitRepository.query(`
            select profit.* from profit
            inner join answer on answer.id = profit.answer_id
            where answer.video_id = ? and profit.status = 1 and profit.type != 0
          `, [video_id])
          //删除悬赏
          await this.rewardSuccessRepository.createQueryBuilder(null, queryRunner)
            .delete()
            .where({ video_id: video_id, wx_user: In(profitList.map(e => e.use_wx_user)) })
            .execute()
          await this.rewardRepository.createQueryBuilder(null, queryRunner)
            .update({ pay_status: payStatusEnum.reject })
            .where({ video_id: video_id, wx_user: In(profitList.map(e => e.use_wx_user)) })
            .execute()

          if (profitList.length > 0) {
            await this.profitRepository.createQueryBuilder(null, queryRunner)
              .delete()
              .where({ id: In(profitList.map(e => e.id)) })
              .execute()
          }
          let refundProfitUnLockHomeList = await this.profitUnLockHomeRepository.find({ where: { video_id: video_id, status: EnumProfitUnLockHome_Status.entry } })
          if (refundProfitUnLockHomeList.length > 0) {
            await this.profitUnLockHomeRepository.createQueryBuilder(null, queryRunner)
              .delete()
              .where({ id: In(refundProfitUnLockHomeList.map(e => e.id)) })
              .execute()
          }
          refundProfitUnLockHomeList.map((e: any) => e.refund_type = 'unlock')

          let refundList: ProfitRefund[] = []
          let list = [...profitList, ...refundProfitUnLockHomeList]
          list.filter(e => e.unit_price > 0).map((findProfit: any) => {
            //添加收益退款记录
            let profitRefund = new ProfitRefund()
            profitRefund.answer_id = findProfit.answer_id
            profitRefund.author_wx_user = findProfit.author_wx_user
            profitRefund.use_wx_user = findProfit.use_wx_user
            profitRefund.status = profitRefundStatusEnum.refoundSuccess
            profitRefund.notes = findProfit.notes
            profitRefund.service_charge = findProfit.service_charge
            profitRefund.unit_price = findProfit.unit_price
            profitRefund.type = findProfit.type
            profitRefund.update_time = findProfit.update_time
            profitRefund.create_time = findProfit.create_time
            profitRefund.refund_type = findProfit.refund_type === 'unlock' ? EnumProfitRefundType.unlock_home : EnumProfitRefundType.profit
            refundList.push(profitRefund)


            //通知申请人已退款
            let notice = new Notices()
            notice.answer_id = findProfit.answer_id
            notice.check = NoticeCheckEnum.yes
            notice.create_time = new Date()
            notice.type = NoticeTypeEnum.refund_accept
            notice.video_id = video_id
            notice.wx_user = findProfit.use_wx_user
            noticeList.push(notice)
          })
          await this.profitRefundRepository.createQueryBuilder(null, queryRunner)
            .insert()
            .into(ProfitRefund)
            .values(refundList)
            .execute()

          await Promise.all(list.map(async e => {
            //清空消费记录缓存
            await this.redisCacheService.clear(`${e.use_wx_user}:consume_list:consume*`)
            await this.redisCacheService.clear(`${e.use_wx_user}:consume_total:consume*`)
            await this.redis.del(`payconsumption:wallet:${e.use_wx_user}`)
          }))
        } else {
          await this.answerRepository.createQueryBuilder(null, queryRunner).update({ ic_group: video.ic_group, update_time: new Date() }).where({ id: answer_id }).execute()
        }
      } else if (video.ic_group) {
        //添加新答案
        let answer = new Answer()
        answer.ic_group = video.ic_group
        answer.check = CheckEnum.yes
        answer.wx_user = system_wx_user
        answer.check_time = new Date()
        answer.create_time = new Date()
        answer.type = TypeEnum.works
        answer.video_id = video_id
        let addAnswerResult = await this.answerRepository.createQueryBuilder(null, queryRunner).insert().into(Answer).values(answer).execute()

        //查询所有同提问
        let questionList = await this.questionsIcRepository.find({ where: { video_id: video_id, post_answer: null, delete_tag: 0 } })
        if (questionList.length > 0) {
          await this.questionsIcRepository.createQueryBuilder(null, queryRunner)
            .update({ answer_time: new Date(), post_answer: 1 })
            .where({ id: In(questionList.map(e => e.id)) })
            .execute()
          questionList.map(e => {
            postMyData.push({ video_id: e.video_id, wx_user: e.wx_user })
          })
        }

        if (addAnswerResult.identifiers?.[0]?.id) {
          let newAnswerId = addAnswerResult.identifiers[0].id
          //查询悬赏过的
          let rewardSuccessList = await this.rewardSuccessRepository.find({ where: { video_id: video_id } })
          //添加观看权限
          let insertProfitList = []
          rewardSuccessList.map(e => {
            let profit = new Profit()
            profit.answer_id = newAnswerId
            profit.author_wx_user = answer.wx_user
            profit.create_time = new Date()
            profit.status = profitEnum.entry
            profit.type = profitTypeEnum.consume
            profit.update_time = new Date()
            profit.use_wx_user = e.wx_user
            profit.unit_price = e.unit_price - e.service_charge
            profit.service_charge = e.service_charge
            insertProfitList.push(profit)
          })
          if (insertProfitList.length > 0) {
            await this.profitRepository.createQueryBuilder(null, queryRunner).insert().into(Profit).values(insertProfitList).execute()
          }
        }
      }

      if (findRefundIngList.length > 0) {
        let index = 0
        let loopdel = async () => {
          let item = findRefundIngList[index]
          //退款
          //修改同提问答案收到的时间
          //清空同提问时间
          await this.questionsIcRepository.createQueryBuilder(null, queryRunner)
            .update({ answer_time: new Date(), post_answer: null })
            .where({ video_id: item.video_id, wx_user: item.use_wx_user })
            .execute()
          //删除悬赏
          await this.rewardSuccessRepository.createQueryBuilder(null, queryRunner)
            .delete()
            .where({ video_id: item.video_id, wx_user: item.use_wx_user })
            .execute()
          await this.rewardRepository.createQueryBuilder(null, queryRunner)
            .update({ pay_status: payStatusEnum.reject })
            .where({ video_id: item.video_id, wx_user: item.use_wx_user })
            .execute()
          index++
          if (index < findRefundIngList.length - 1) {
            await loopdel()
          }
        }
        await loopdel()


        let refundProfitList = findRefundIngList.filter(e => e.refund_type === 'profit')
        if (refundProfitList.length > 0) {
          await this.profitRepository.createQueryBuilder(null, queryRunner)
            .delete()
            .where({ id: In(findRefundIngList.map(e => e.id)) })
            .execute()
        }
        let refundProfitUnLockHomeList = findRefundIngList.filter(e => e.refund_type === 'profit_unlock_home')
        if (refundProfitUnLockHomeList.length > 0) {
          await this.profitUnLockHomeRepository.createQueryBuilder(null, queryRunner)
            .delete()
            .where({ id: In(refundProfitUnLockHomeList.map(e => e.id)) })
            .execute()
        }

        let refundList: ProfitRefund[] = []
        findRefundIngList.map(findProfit => {
          //添加收益退款记录
          let profitRefund = new ProfitRefund()
          profitRefund.answer_id = findProfit.answer_id
          profitRefund.author_wx_user = findProfit.author_wx_user
          profitRefund.use_wx_user = findProfit.use_wx_user
          profitRefund.status = profitRefundStatusEnum.refoundSuccess
          profitRefund.notes = findProfit.notes
          profitRefund.service_charge = findProfit.service_charge
          profitRefund.unit_price = findProfit.unit_price
          profitRefund.type = findProfit.type
          profitRefund.update_time = findProfit.update_time
          profitRefund.create_time = findProfit.create_time
          profitRefund.refund_type = findProfit.refund_type === 'profit' ? EnumProfitRefundType.profit : EnumProfitRefundType.unlock_home
          refundList.push(profitRefund)

          //通知申请人已退款
          let notice = new Notices()
          notice.answer_id = findProfit.answer_id
          notice.check = NoticeCheckEnum.yes
          notice.create_time = new Date()
          notice.type = NoticeTypeEnum.refund_accept
          notice.video_id = findProfit.video_id
          notice.wx_user = findProfit.use_wx_user
          noticeList.push(notice)
        })
        await this.profitRefundRepository.createQueryBuilder(null, queryRunner)
          .insert()
          .into(ProfitRefund)
          .values(refundList)
          .execute()
      }

      //重置所有人的报错
      if (findReportList.length > 0) {
        await this.answerReportErrorsRepository.createQueryBuilder(null, queryRunner)
          .update({ reset_error: 1 })
          .where({ answer_id: findAnswer[0].id, delete_tag: 0, reset_error: 0 })
          .execute()
        //给所有报错人通知出处已修正
        findReportList.map(e => {
          //添加通知
          let notice = new Notices()
          notice.video_id = findVideo.id
          notice.answer_id = e.answer_id
          notice.wx_user = e.wx_user
          notice.create_time = new Date()
          notice.type = NoticeTypeEnum.answer_is_update
          notice.content = '该视频出处已修正'
          noticeList.push(notice)
        })
      }
      if (noticeList.length > 0) {
        await this.noticesRepository.createQueryBuilder(null, queryRunner).insert().into(Notices).values(noticeList).execute()
      }
      //查询所有关注此网红的人
      if (concernList.length > 0) {
        await this.wxUserRepository.createQueryBuilder(null, queryRunner).update({ concern_is_update: 1 }).where({ openid: In(concernList.map(e => e.wx_user)) }).execute()
      }
      await queryRunner.commitTransaction()
      await queryRunner.release();

      findRefundIngList.map(findProfit => {
        WXAPIOBJ.clearPayWallet(findProfit.use_wx_user)
        this.wsStartGateway.postUpdateNotice(findProfit.use_wx_user)
        this.wsStartGateway.postUpdateVideo(findProfit.video_id)
      })

      if (findVideo.ic_group) {
        //清空关注数据
        await this.redisCacheService.clear(`*:icinfo:icgroup:${findVideo.ic_group}:videos`)
        await this.redisCacheService.clear(`icinfo:icgroup:${findVideo.ic_group}*`)
      }
      if (video.ic_group) {
        //清空关注数据
        await this.redisCacheService.clear(`*:icinfo:icgroup:${video.ic_group}:videos`)
        await this.redisCacheService.clear(`icinfo:icgroup:${video.ic_group}*`)
      }
      //清空视频缓存
      await this.redisCacheService.clear(`videos:${video_id}*`)

      postMyData.map(e => {
        this.wsStartGateway.postUpdateMyData(e.wx_user, e.video_id)
      })
      let noticeWxUser = [...new Set([...noticeList.map(e => e.wx_user)])]
      noticeWxUser.map(wx_user => {
        this.wsStartGateway.postUpdateNotice(wx_user)
      })

      concernList.map(e => {
        this.wsStartGateway.postUpdateConcern(e.wx_user)
      })

      if (findRefundIngList.indexOf(video_id) == -1) {
        this.wsStartGateway.postUpdateVideo(video_id)
      }

    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err.toString()
    }
  }

  // @Timeout(1000)
  // async getlist(){
  //   let list = await this.videoRepository.query(`
  //     select video.id, video.basic_reward, video.basic_questions from video where ic_group is null
  //   `, [])
  //   let txt = []
  //   list.map(e => {
  //     txt.push(` update video set basic_reward = ${this.getRandomNumber(100, 1000)} where video.id = ${e.id} and ic_group is null;`)
  //   })
  //   writeFileSync(join(__dirname, 'sql2.sql'), txt.join('\r\n'))
  //   // console.log(txt[0])
  // }

  async update_video_library(video: Video): Promise<any> {
    let wx_user = video.wx_user
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    let video_id = video.id
    //查询视频的回答
    let findAnswer: Answer[] = await this.answerRepository.query(`
      select a.* from answer a
      where a.video_id = ? and a.wx_user = ?
      order by a.id asc
    `, [video_id, wx_user])
    //查询视频原始数据
    let findVideo = await this.videoRepository.findOne({ where: { id: video_id } })

    // 开始事务
    await queryRunner.startTransaction()
    try {
      if (findVideo.original != video.original) {
        video.id_card = this.getIDCard(video.original == OriginalEnum.yes)
      }
      await queryRunner.manager.update(Video, { id: video_id }, video);

      if (findAnswer.length > 0) {
        let addAnswer: Answer = findAnswer[0]
        let answer_id = addAnswer.id
        if (!video.ic_group) {
          //删除答案
          await this.answerRepository.createQueryBuilder(null, queryRunner).delete().where({ id: answer_id }).execute()
        } else {
          await this.answerRepository.createQueryBuilder(null, queryRunner).update({ ic_group: video.ic_group, update_time: new Date() }).where({ id: answer_id }).execute()
        }
      } else if (video.ic_group) {
        //添加新答案
        let answer = new Answer()
        answer.ic_group = video.ic_group
        answer.check = CheckEnum.yes
        answer.wx_user = system_wx_user
        answer.check_time = new Date()
        answer.create_time = new Date()
        answer.type = TypeEnum.works
        answer.video_id = video_id
        await this.answerRepository.createQueryBuilder(null, queryRunner).insert().into(Answer).values(answer).execute()
      }

      await queryRunner.commitTransaction()
      await queryRunner.release();
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err.toString()
    }
  }

  async create_video_library(video: Video): Promise<any> {
    let wx_user = video.wx_user
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      //创建一个视频
      let saveVideo = await queryRunner.manager.save(video);
      if (!saveVideo) {
        throw new Error('创建视频失败')
      }
      const video_id = saveVideo.id
      //添加一个回答
      let addAnswer = new Answer()
      addAnswer.video_id = video_id
      addAnswer.wx_user = wx_user
      addAnswer.create_time = new Date()
      addAnswer.check = CheckEnum.yes
      addAnswer.check_time = new Date()
      addAnswer.type = TypeEnum.works
      // addAnswer.answer = answer.join(',')
      // addAnswer.img = imgs.join(',')
      // addAnswer.img_id = img_ids.join(',')
      const saveAnswer: Answer = await queryRunner.manager.save(addAnswer)
      let answer_id = saveAnswer.id


      //查询所有平台
      let findPlatformList = await this.platformRepository.query(`
        select a.id as id_platform,a.platform,a.wx_user,b.id as id_ic,b.name as ic_name,b.img,b.img_id from platform a
        inner join internet_celebrity b on b.platform = a.id and b.wx_user = a.wx_user
        where a.ic_group = ?
        order by a.id asc
      `, [video.ic_group])

      let len = findPlatformList.length
      let run = () => {
        return new Promise((resolve, reject) => {
          //添加回答详情
          findPlatformList.map(async e => {
            let addAnswerInfo = new AnswerInfo()
            addAnswerInfo.answer_id = answer_id
            addAnswerInfo.create_time = new Date()
            addAnswerInfo.ic_name = e.ic_name
            addAnswerInfo.img = e.img
            addAnswerInfo.img_id = e.img_id
            addAnswerInfo.platform = e.platform
            addAnswerInfo.video_id = video_id
            await queryRunner.manager.save(addAnswerInfo)
            len--
            if (len === 0) {
              resolve(true)
            }
          })
        })
      }
      if (len > 0) {
        await run()
      }

      await queryRunner.commitTransaction()
      await queryRunner.release();
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }

  async update(video: Video): Promise<Video> {
    return await this.videoRepository.save(video);
  }

  async updateInIc(id: number, in_ic: number) {
    let findVideo = await this.videoRepository.findOne({ where: { id: id } })
    //查询视频的网红还有没有主页，如果没有，把所有关注此网红的数据清空
    let findConcerns = [], findUnConcerns = [], ic_name = '', clear_ic = false
    if (in_ic == 0 && findVideo.ic_group) {
      let findFullVideoCount = await this.videoRepository.query(`
        select count(1) as total from (
          select distinct v.id from video as v
          inner join platform on platform.ic_group = v.ic_group
          inner join internet_celebrity_group on internet_celebrity_group.id = v.ic_group
          where v.check = 1 and
            (
              (internet_celebrity_group.type = 0 and platform.platform in (select setting.value from setting where setting.key = 'level3'))
              or (
                (
                  internet_celebrity_group.type = 3 
                  or internet_celebrity_group.type = 2
                  or (v.overseas = 3 and internet_celebrity_group.type = 0 and v.original = 1)
                )
                and v.source != 2
              )
            ) and internet_celebrity_group.delete_tag = 0
            and 
              (
                -- 提问视频，进入网红主页
                (
                  v.type = 0 and v.original = 0 and v.in_ic = 1
                )
                -- 非认证作品，进入网红主页
                or (
                  v.overseas = 3 and v.profit_type = 1 and v.in_ic = 1
                )
                -- 认证作品，看完整版
                or (
                  v.overseas = 1 and v.profit_type = 1
                )
                -- 视频库视频
                or (
                  v.overseas = 0 and v.type = 0 and (v.in_ic = 1 or v.in_ic is null)
                )
              )
            and v.ic_group = ? 
        ) video
      `, [findVideo.ic_group])
      if (findFullVideoCount[0].total == 1) {
        clear_ic = true
        //查询所有关联此网红的人
        findConcerns = await this.concernRepository.find({ where: { concern_ic_group: findVideo.ic_group } })
        //查询所有取消关联的网红
        findUnConcerns = await this.unConcernRepository.find({ where: { concern_ic_group: findVideo.ic_group } })

        let icInfo = await this.internetCelebrityRepository.findOne({ where: { ic_group: findVideo.ic_group } })
        ic_name = icInfo.name
      }
    }
    console.log(in_ic, clear_ic, findConcerns, '-====================')
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      // this.videoRepository.update({id:id},{in_ic: in_ic === 0 ? EnumInIc.no : EnumInIc.yes})
      //修改审核状态
      await this.videoRepository.createQueryBuilder(null, queryRunner)
        .update({
          in_ic: in_ic === 0 ? EnumInIc.no : EnumInIc.yes
        })
        .where({ id: id })
        .execute()

      if (in_ic == 0 && clear_ic) {
        //创建关联此网红的人的关联记录
        let unConcernsList = []
        findConcerns.filter(e => {
          return findUnConcerns.find(c => c.concern_id == e.id && c.name == ic_name && c.wx_user == e.wx_user) ? false : true
        }).map(e => {
          let unconcern = new UnConcern()
          unconcern.name = ic_name
          unconcern.create_time = new Date()
          unconcern.concern_ic_group = findVideo.ic_group
          unconcern.wx_user = e.wx_user
          unconcern.concern_id = e.id
          unConcernsList.push(unconcern)
        })
        if (unConcernsList.length > 0) {
          await this.unConcernRepository.createQueryBuilder(null, queryRunner)
            .insert()
            .into(UnConcern)
            .values(unConcernsList)
            .execute()
        }
        //删除所有关联此网红的人
        await this.concernRepository.createQueryBuilder(null, queryRunner).delete().where({ concern_ic_group: findVideo.ic_group }).execute()
      }

      await queryRunner.commitTransaction()
      await queryRunner.release();

      //清空缓存-视频
      await this.redisCacheService.del(`videos:${id}:basic`)
      //清空缓存-关注详情
      if (findVideo?.ic_group) {
        if (clear_ic) {
          await this.redisCacheService.clear(`*:icinfo:icgroup:${findVideo.ic_group}*`)
          await this.redisCacheService.clear(`icinfo:icgroup:${findVideo.ic_group}*`)
        } else {
          await this.redisCacheService.clear(`*:icinfo:icgroup:${findVideo.ic_group}:videos`)
        }
      }
      this.wsStartGateway.postUpdateVideo(id)
      //更新我的数据
      this.wsStartGateway.postUpdateMyData(findVideo.wx_user, findVideo.id)
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }

  /**
   * 视频/图片审核
   * @param id 
   * @param check 
   * @returns 
   */
  async updateCheck(id: number, check: number, isic?: boolean): Promise<any> {
    //查询视频详情
    let findVideo = await this.videoRepository.findOne({ where: { id: id } })
    if (!findVideo) {
      return '视频不存在'
    }
    //查询视频是否是今天之前的视频
    let startTime = utils.Format(new Date(findVideo.create_time), 'yyyy-MM-dd')
    let nowTime = utils.Format(new Date(), 'yyyy-MM-dd')
    if (startTime !== nowTime) {
      //验证今天之前的视频当天是否删除了20次了
      startTime = new Date()
      let endTime = new Date()
      endTime.setHours(23)
      endTime.setMinutes(59)
      endTime.setSeconds(59)

      const limit = await this.rateLimiter.consume_manager('update_check', 1, (endTime.getTime() - startTime.getTime()) / 1000)
      if (!limit) {
        return '上/下架超过限制，请明日再试！'
      }
    }


    //查询视频的网红还有没有主页，如果没有，把所有关注此网红的数据清空
    let findConcerns = [], findUnConcerns = [], ic_name = '', clear_ic = false
    if (isic && findVideo.ic_group) {
      let findFullVideoCount = await this.videoRepository.query(`
        select count(1) as total from (
          select distinct v.id from video as v
          inner join platform on platform.ic_group = v.ic_group
          inner join internet_celebrity_group on internet_celebrity_group.id = v.ic_group
          where v.check = 1 and
            (
              (internet_celebrity_group.type = 0 and platform.platform in (select setting.value from setting where setting.key = 'level3'))
              or (
                (
                  internet_celebrity_group.type = 3 
                  or internet_celebrity_group.type = 2
                  or (v.overseas = 3 and internet_celebrity_group.type = 0 and v.original = 1)
                )
                and v.source != 2
              )
            ) and internet_celebrity_group.delete_tag = 0
            and 
              (
                -- 提问视频，进入网红主页
                (
                  v.type = 0 and v.original = 0 and v.in_ic = 1
                )
                -- 非认证作品，进入网红主页
                or (
                  v.overseas = 3 and v.profit_type = 1 and v.in_ic = 1
                )
                -- 认证作品，看完整版
                or (
                  v.overseas = 1 and v.profit_type = 1
                )
                -- 视频库视频
                or (
                  v.overseas = 0 and v.type = 0 and (v.in_ic = 1 or v.in_ic is null)
                )
              )
            and v.ic_group = ? 
        ) video
      `, [findVideo.ic_group])
      if (findFullVideoCount[0].total == 1) {
        clear_ic = true
        //查询所有关联此网红的人
        findConcerns = await this.concernRepository.find({ where: { concern_ic_group: findVideo.ic_group } })
        //查询所有取消关联的网红
        findUnConcerns = await this.unConcernRepository.find({ where: { concern_ic_group: findVideo.ic_group } })

        let icInfo = await this.internetCelebrityRepository.findOne({ where: { ic_group: findVideo.ic_group } })
        ic_name = icInfo.name
      }
    }


    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      // await this.videoRepository.update({id:id},{check:check})
      await this.videoRepository.createQueryBuilder(null, queryRunner).update({ check: check, disabled: check == 0 ? 1 : 0 }).where({ id: id }).execute()
      if (clear_ic) {
        //创建关联此网红的人的关联记录
        let unConcernsList = []
        findConcerns.filter(e => {
          return findUnConcerns.find(c => c.concern_id == e.id && c.name == ic_name && c.wx_user == e.wx_user) ? false : true
        }).map(e => {
          let unconcern = new UnConcern()
          unconcern.name = ic_name
          unconcern.create_time = new Date()
          unconcern.concern_ic_group = findVideo.ic_group
          unconcern.wx_user = e.wx_user
          unconcern.concern_id = e.id
          unConcernsList.push(unconcern)
        })
        if (unConcernsList.length > 0) {
          await this.unConcernRepository.createQueryBuilder(null, queryRunner)
            .insert()
            .into(UnConcern)
            .values(unConcernsList)
            .execute()
        }
        //删除所有关联此网红的人
        await this.concernRepository.createQueryBuilder(null, queryRunner).delete().where({ concern_ic_group: findVideo.ic_group }).execute()
      }


      await queryRunner.commitTransaction()
      await queryRunner.release();

      //清空缓存-视频
      await this.redisCacheService.del(`videos:${id}:basic`)
      //清空缓存-关注详情
      if (findVideo?.ic_group) {
        if (clear_ic) {
          await this.redisCacheService.clear(`*:icinfo:icgroup:${findVideo.ic_group}*`)
          await this.redisCacheService.clear(`icinfo:icgroup:${findVideo.ic_group}*`)
        } else {
          await this.redisCacheService.clear(`*:icinfo:icgroup:${findVideo.ic_group}:videos`)
        }
      }

      this.wsStartGateway.postUpdateVideo(id)
      //更新我的数据
      this.wsStartGateway.postUpdateMyData(findVideo.wx_user, findVideo.id)

    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }


  /**
   * 视频/图片审核
   * @param id 
   * @param check 
   * @returns 
   */
  async updateCheckManager(id: number, check: number): Promise<any> {
    let result = await this.videoRepository.update({ id: id }, { check: check })
    this.wsStartGateway.postUpdateVideo(id)
    return result

    // //查询视频详情
    // let findVideo = await this.videoRepository.findOne({where:{id:id}})
    // if(!findVideo){
    //   return '视频不存在'
    // }
    // let db: DataBase = new DataBase()
    // let connection = await db.getConnection()
    // const queryRunner = connection.createQueryRunner()
    // await queryRunner.connect()
    // // 开始事务
    // await queryRunner.startTransaction()
    // try {
    //   //添加通知
    //   let notice = new Notices()
    //   notice.create_time = new Date()
    //   notice.video_id = id
    //   notice.wx_user = findVideo.wx_user
    //   notice.check = check
    //   let updateVideoParams:any = {check:check,check_time:new Date()}
    //   //提问
    //   if(findVideo.original == 0){
    //     notice.type = NoticeTypeEnum.question_accept
    //     //修改作品所属为提问仓库用户
    //     if(findVideo.wx_user !== question_store_wx_user){
    //       updateVideoParams.wx_user = question_store_wx_user
    //       updateVideoParams.wx_user_source = findVideo.wx_user
    //       //添加视频原有用户为同提问
    //       let question = new Questions()
    //       question.video_id = findVideo.id
    //       question.create_time = new Date()
    //       question.wx_user = findVideo.wx_user
    //       await this.questionsIcRepository.createQueryBuilder(null, queryRunner).insert().into(Questions).values(question).execute()
    //     }
    //     //系统用户同提问
    //     // let question2 = new Questions()
    //     // question2.video_id = findVideo.id
    //     // question2.create_time = new Date()
    //     // question2.wx_user = system_wx_user
    //     // await this.questionsIcRepository.createQueryBuilder(null, queryRunner).insert().into(Questions).values(question2).execute()

    //   } else if(findVideo.original == 1){//作品
    //     notice.type = NoticeTypeEnum.works_accept
    //   }
    //   //添加通知
    //   await queryRunner.manager.save(notice)
    //   //修改审核状态
    //   await this.videoRepository.createQueryBuilder(null,queryRunner).update(updateVideoParams).where({id:id}).execute()

    //   await queryRunner.commitTransaction()
    //   await queryRunner.release();
    // } catch (err) {
    //   // 有错误做出回滚更改
    //   await queryRunner.rollbackTransaction()
    //   await queryRunner.release();
    //   return err
    // }
  }


  async updateCheckText(id: number, check_text: number): Promise<any> {
    //查询视频详情
    let findVideo = await this.videoRepository.findOne({ where: { id: id } })
    if (!findVideo) {
      return '视频不存在'
    }
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      //添加通知
      let notice = new Notices()
      notice.create_time = new Date()
      notice.video_id = id
      notice.wx_user = findVideo.wx_user
      notice.check = 0
      //提问
      if (findVideo.original == 0) {
        notice.type = NoticeTypeEnum.question_reject
      } else if (findVideo.original == 1) {//作品
        notice.type = NoticeTypeEnum.works_reject
      }
      //添加通知
      await queryRunner.manager.save(notice)
      //修改审核状态
      await this.videoRepository.createQueryBuilder(null, queryRunner).update({ check_text: check_text, check_text_time: new Date() }).where({ id: id }).execute()
      await queryRunner.commitTransaction()
      await queryRunner.release();
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }


  }

  async updateIcGroup(id: number, ic_group: number): Promise<void> {
    //查询视频详情
    let findVideo = await this.videoRepository.findOne({ where: { id: id } })
    if (findVideo) {
      let updateParams: any = { ic_group: ic_group, original: OriginalEnum.yes }
      if (!findVideo.ic_group_source && ic_group) {
        updateParams.ic_group_source = ic_group
      }
      await this.videoRepository.update({ id: id }, updateParams)
    }
  }

  /**
   * 删除我的提问（假删除）
   * @param id 
   * @param wx_user 
   */
  async delete_my_question(id: number, wx_user: string): Promise<any> {
    let findVideo = await this.videoRepository.query(`
      select * from video
      inner join answer on answer.video_id = video.id
      where video.id = ? and video.wx_user = ? and answer.check = 1 and video.isreward = 0 and video.original = 0
    `, [id, wx_user])
    if (findVideo.length > 0) {
      await this.noticesRepository.update({ video_id: id, wx_user: wx_user }, { is_delete: NoticeIsDeleteEnum.yes })
      let result = await this.videoRepository.update({ id: id }, { delete_tag: DeleteTagEnum.yes })
      if (result.affected > 0) {
        return { success: true }
      } else {
        return { success: false, msg: '删除失败' }
      }
    } else {
      return { success: false, msg: '没找到提问' }
    }
  }

  /**
   * 删除视频
   * @param id 
   * @returns 
   */
  async delete(id: number, wx_user: string, deleteResource: Function): Promise<any> {
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    //查询视频详情
    let findVideo = await this.videoRepository.findOne({ where: { id: id } })
    if (findVideo.isreward != 1 && findVideo.wx_user != wx_user) {
      return '此视频不属于你。'
    }

    //删除二类作品之前必须先填出处信息，或者先清空一类，再删除二类
    if (findVideo.original == 1 && findVideo.overseas == 1 && findVideo.profit_type == 1) {
      //判断是否是二类作品
      let is_look_full_video = await this.videoRepository.query(`
        select * from (
          select count(1) cou from video as v
          inner join platform on platform.ic_group = v.ic_group
          inner join internet_celebrity_group on internet_celebrity_group.id = v.ic_group
          where v.wx_user = ? and v.overseas = 1 and v.profit_type = 0 and v.original = 1 and v.delete_tag = 0
        ) video
        union all
        select count(1) cou from internet_celebrity_group 
        inner join platform on platform.ic_group = internet_celebrity_group.id
        where internet_celebrity_group.wx_user = ? and internet_celebrity_group.type = 2
          and platform.platform is not null and platform.platform != ''
        union all
        select count(1) from video
        where video.wx_user = ? and video.id != ? and video.overseas = 1 and video.profit_type = 1 and video.original = 1 and video.delete_tag = 0
      `, [wx_user, wx_user, wx_user, id])
      if (Number(is_look_full_video[0].cou || 0) > 0 && Number(is_look_full_video[1].cou || 0) == 0 && Number(is_look_full_video[2].cou || 0) == 0) {
        return '您同时拥有Ⅰ类、Ⅱ类作品，删除Ⅱ类作品前需填写社交平台信息，或先清空Ⅰ类作品，再删除当前Ⅱ类视频。'
      }
    }

    //如果是多图，删除所有图片
    let multiImgList: MultiImg[] = []
    if (findVideo.type === VideoEnum.image && findVideo.original == OriginalEnum.yes) {
      //查询所有图片
      multiImgList = await this.multiImgRepository.find({ where: { video_id: findVideo.id } })
    }
    //如果是悬赏视频
    let reward_order: Reward
    let rewardList: Reward[] = []
    if (findVideo.isreward == IsRewardEnum.yes) {
      rewardList = await this.rewardRepository.find({ where: { video_id: id, pay_status: payStatusEnum.success } })
      if (rewardList.length > 0) {
        //当前用户的悬赏
        reward_order = rewardList.find(e => e.wx_user == wx_user)
      }
    }
    try {
      //撤回可以直接删除资源，因为视频没有审核通过
      //删除一个视频
      //如果是未认证的作品转移到系统用户身上，并且进入视频库
      if (findVideo.overseas === OverseasEnum.virtual && findVideo.original === OriginalEnum.yes && findVideo.check === 1) {
        //原始用户的作品设置为已删除
        await this.videoRepository.createQueryBuilder(null, queryRunner).update({
          delete_tag: DeleteTagEnum.yes
        }).where({ id: id }).execute()
        //给系统用户添加视频
        let addVideoToSystem = new Video()
        addVideoToSystem.video_id = findVideo.video_id
        addVideoToSystem.video_url = findVideo.video_url
        addVideoToSystem.video_url_source = findVideo.video_url_source
        addVideoToSystem.video_cover = findVideo.video_cover
        addVideoToSystem.create_time = new Date()
        addVideoToSystem.update_time = new Date()
        addVideoToSystem.video_ratio = findVideo.video_ratio
        addVideoToSystem.ic_group = findVideo.ic_group
        addVideoToSystem.wx_user = system_wx_user
        addVideoToSystem.check = 1
        addVideoToSystem.type = findVideo.type
        addVideoToSystem.original = findVideo.original
        addVideoToSystem.check_time = new Date()
        addVideoToSystem.source = SourceEnum.robot
        addVideoToSystem.profit_type = findVideo.profit_type
        addVideoToSystem.check_text = findVideo.check_text
        addVideoToSystem.check_text_time = findVideo.check_text_time
        addVideoToSystem.filemd5 = findVideo.filemd5
        addVideoToSystem.isreward = findVideo.isreward
        addVideoToSystem.overseas = OverseasEnum.no
        addVideoToSystem.id_card = this.getIDCard(true)
        addVideoToSystem.is_home = findVideo.is_home
        addVideoToSystem.wx_user_source = findVideo.wx_user_source
        addVideoToSystem.ic_group_source = findVideo.ic_group_source
        let addVideoResult = await this.videoRepository.createQueryBuilder(null, queryRunner).insert().into(Video).values(addVideoToSystem).execute()
        //创建答案
        let addAnswerToSystem = new Answer()
        addAnswerToSystem.video_id = addVideoResult.identifiers[0].id
        addAnswerToSystem.wx_user = system_wx_user
        addAnswerToSystem.create_time = new Date()
        addAnswerToSystem.check = 1
        addAnswerToSystem.check_time = new Date()
        addAnswerToSystem.type = 2
        addAnswerToSystem.update_time = new Date()
        await this.answerRepository.createQueryBuilder(null, queryRunner).insert().into(Answer).values(addAnswerToSystem).execute()
        //给原始用户创建视频访问记录，让他刷不到此视频
        let addWatchRecord = new WatchRecord()
        addWatchRecord.video_id = addAnswerToSystem.video_id
        addWatchRecord.create_time = new Date()
        addWatchRecord.wx_user = findVideo.wx_user
        await this.watchRecordRepository.createQueryBuilder(null, queryRunner).insert().into(WatchRecord).values(addWatchRecord).execute()
        //修改多图到新视频上
        if (multiImgList.length > 0) {
          await this.multiImgRepository.createQueryBuilder(null, queryRunner).update({ video_id: addAnswerToSystem.video_id }).where({ video_id: findVideo.video_id }).execute()
        }
      } else {
        await this.videoRepository.createQueryBuilder(null, queryRunner).delete().where({ id: id }).execute()
        if (multiImgList.length > 0) {
          //删除所有多图
          await this.multiImgRepository.createQueryBuilder(null, queryRunner).delete().where({ video_id: id }).execute()
          //删除多图资源
          for (let i = 0; i < multiImgList.length; i++) {
            await deleteResource(multiImgList[i].img_id, video_SubAppId)
          }
        }
        //删除云资源
        await deleteResource(findVideo.video_id, video_SubAppId)
      }
      //设置通知为删除标准
      await this.noticesRepository.createQueryBuilder(null, queryRunner).update({ is_delete: NoticeIsDeleteEnum.yes })
        .where({ video_id: findVideo.video_id, wx_user: wx_user }).execute()
      // }
      //退款
      if (reward_order) {
        //修改状态为已退款
        await this.rewardRepository.createQueryBuilder(null, queryRunner).update({ pay_status: payStatusEnum.reject }).where({ id: reward_order.id, wx_user: wx_user }).execute()
        await this.rewardSuccessRepository.createQueryBuilder(null, queryRunner).delete().where({ video_id: reward_order.video_id, wx_user: wx_user }).execute()
        await WXAPIOBJ.clearPayWallet(wx_user)
        // await WXAPIOBJ.refunds(wx_user, reward_order.pay_order, reward_order.unit_price)
      }


      await queryRunner.commitTransaction()
      await queryRunner.release();
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }

  findAllGlobal() {
    return this.videoRepository.find({ where: { type: 0, video_id: Not('') } })
  }

  changeIsHome(video_id: number, is_home: EnumIsHome) {
    let isHomeVal = -1
    if (is_home === EnumIsHome.yes) {
      isHomeVal = EnumIsHome.yes
    } else if (is_home === EnumIsHome.no) {
      isHomeVal = EnumIsHome.no
    }
    if (isHomeVal === -1) {
      return new Error('传参错误')
    }
    return this.videoRepository.update({ id: video_id }, { is_home: isHomeVal })
  }

  sample(arr, n) {
    let result = new Array();
    let random;
    let index;
    if (n > arr.length) {
      throw new Error("样本大小大于数组长度");
    }
    for (let i = 0; i < n; i++) {
      do {
        random = Math.floor(Math.random() * arr.length);
        index = random;
      } while (index in result);
      result[index] = arr[random];
    }
    return Object.values(result);
  }

  async generBasicReward() {
    let list = await this.videoRepository.query(`
      select * from video
      where video.basic_reward > 0
    `, [])

    let sql = []
    list.map(e => {
      let rand = Number(e.basic_reward) + this.getRandomNumber(1, 9) * 30
      sql.push(`update video set basic_reward=${rand} where id=${e.id}`)
    })
    let txt = sql.join(';\r\n')
    writeFileSync(join(__dirname, 'sql.txt'), txt)
  }

  async generBasicQuestion() {
    let list = await this.videoRepository.query(`
      select video.id from video
      where video.check = 1 and video.delete_tag = 0 and video.ic_group is not null and video.is_home = 1
      and video.id not in (
        select video.id from video
        where video.check = 1 and (
          video.ic_group in (
            select a.id from (
              select distinct internet_celebrity_group.id from internet_celebrity_group 
              left join platform on platform.ic_group = internet_celebrity_group.id
              inner join video on video.ic_group = internet_celebrity_group.id
              where (
                (
                  internet_celebrity_group.type = 2 
                )
                or(
                  internet_celebrity_group.type = 0 and (
                    platform.platform in (select setting.value from setting where setting.key = 'level3')
                    or (select count(1) from platform where platform.platform != '' and platform.ic_group = internet_celebrity_group.id) = 0
                  )
                )
                or (
                  internet_celebrity_group.type = 3
                )
              )
            ) a
          )
          or ((video.overseas = 3 or video.overseas = 1) and video.original = 1)
        )
      )
      and video.id not in (
        select video_id from reward_success
        where reward_success.unit_price = 20000
      )
      and video.basic_questions = 0
      and video.source = 2
    `, [])
    let level1 = await this.videoRepository.query(`
      select video.id, 'level1' as level
      from video
      where video.check = 1 
        and video.is_home = 1 
        and video.id not in (
          select video_id from reward_success
          where reward_success.unit_price = 20000
        ) 
        and video.ic_group is null
        and !(
          video.overseas = 3 and video.profit_type = 1 and video.original = 1
        ) and video.source = 2
        and video.basic_questions = 0
      order by id asc
    `, [])
    list.push(...level1)
    let ids = []
    list.map(e => {
      let rand = Math.random() * 100
      if (rand <= 90) {
        // 使用示例
        const arr = [1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000];
        const sampleSize = 1;
        const sampled = this.sample(arr, sampleSize);
        if (sampled.length > 0) {
          rand = sampled[0]
        } else {
          rand = undefined
        }
      } else {
        rand = 10000
      }
      if (rand !== undefined) {
        if (e.level != 'level1') {
          let sj = parseInt(this.getRandomNumber(14, 33))
          let reward_count = rand * (sj / 100)
          let basic_reward = parseInt((reward_count * 30).toString()) + this.getRandomNumber(1, 9) * 30
          ids.push(`update video set basic_questions=${rand}, basic_reward=${basic_reward} where id = ${e.id}`)
        } else {
          ids.push(`update video set basic_questions=${rand} where id = ${e.id}`)
        }
      }
    })
    let txt = ids.join(';\r\n')
    writeFileSync(join(__dirname, 'sql.txt'), txt)
  }


  getRandomNumber(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }

}
